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

ios – Swift – 尝试将dict值读取为Int时的EXC_BAD_ACCESS,第1张

概述假设我有一个这样定义的字典: let path = NSBundle.mainBundle().pathForResource("books", ofType: "plist")let dict = NSDictionary(contentsOfFile: path)let books = dict.objectForKey("Books") as [[String:AnyObject]] 假设我有一个这样定义的字典:

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 not Int

尝试

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

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

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

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

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

总结

以上是内存溢出为你收集整理的ios – Swift – 尝试将dict值读取为Int时的EXC_BAD_ACCESS全部内容,希望文章能够帮你解决ios – Swift – 尝试将dict值读取为Int时的EXC_BAD_ACCESS所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/web/1023421.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-23
下一篇 2022-05-23

发表评论

登录后才能评论

评论列表(0条)

保存