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

标签 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]

最佳答案

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/

相关文章:

ios - 从 viewdidload 调用 avaudiorecorder 调用不好吗?

ios - 在 iOS 12 中获取数据

objective-c - 赋值时崩溃

ios - 如何让程序在加载用户信息后执行 segue?

ios - 两个设备是否具有相同的 'UUID'

ios - 核心数据并发调试

ios - Realm 文件大小是在注销时调用 deleteAll 之后

ios - UIApplication 共享对象未提供预定通知

ios - 将 NSDictionary 值转换为 NSString

ios - 运行时来自 NSDictionary 的 .strings 文件