假设我有一个定义如下的字典:
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]
最佳答案
bookData["chapterNum"] 可能是 String 而不是 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 值
关于ios - Swift - EXC_BAD_ACCESS 尝试将 dict 值读取为 Int 时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24747770/