Swift - 尝试将dict值读取为Int时EXC_BAD_ACCESS

时间:2014-07-14 23:43:47

标签: ios swift nsdictionary exc-bad-access

假设我有一个这样定义的字典:

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]

为什么这样做?

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

但这会导致崩溃:

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

bookData的日志给出了这个:

bookData: [content: whatever, author: John Doe, tags: (
    tagA,
    tagB
), chapterNum: 5]

1 个答案:

答案 0 :(得分:1)

bookData [“chapterNum”]可能是String not Int

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

如果类型不符合您的预期,您将获得nil

如果您从字典中获取字符串,您可以先获取该字符串并尝试将其转换为Int

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

如果您不希望稍后在该函数调用中处理可选的int值