Swift - EXC_BAD_ACCESS when trying to read dict value as Int

Assuming I have a dictionary like this:

let path = NSBundle.mainBundle().pathForResource("books", ofType: "plist")
let dict = NSDictionary(contentsOfFile: path)
let books = dict.objectForKey("Books") as [[String:AnyObject]] 
let rnd = Int(arc4random_uniform((UInt32(books.count))))
let bookData = books[rnd]

Why does it work?

let author = bookData["author"]! as String

But this causes a crash:

let chapterNum = bookData["chapterNum"]! as Int //should be 5, for example

The following is indicated in the bookData log:

bookData: [content: whatever, author: John Doe, tags: (
    tagA,
    tagB
), chapterNum: 5]
+4
source share
1 answer

bookData ["chapterNum"] probably String not Int

to try

let chapterNum = dict["chapterNum"] as? Int

and you will get zero if the type does not match the expected

If you get a string from a dict, you can first get that string and try to turn it into Int

var chapterNum = 0
if let chapterNumString = dict["chapterNum"] as? String {
    if let chapterNumInt = chapterNumString.toInt()? {
        chapterNum = chapterNumInt
    }
}

If you do not want to process the optional int value later in this function call

+1
source

Source: https://habr.com/ru/post/1548418/


All Articles