【发布时间】:2014-09-12 13:35:17
【问题描述】:
试图找到每本书的标题:
var error: NSError?
let path = NSBundle.mainBundle().pathForResource("books", ofType: "json")
let jsonData = NSData.dataWithContentsOfFile(path, options: .DataReadingMappedIfSafe, error: nil)
let jsonDict = NSJSONSerialization.JSONObjectWithData(jsonData, options: nil, error: &error) as NSDictionary
let books = jsonDict["book"]
var bookTitles:[String]
//for bookDict:Dictionary in books {
// println("title: \(bookDict["title"])")
//}
当我取消对最后三行的注释时,Xcode6 beta3 中的一切都乱了套——所有文本都变白了,我得到不断的“SourceKitService Terminated”和“Editor functionality暂时受限”弹出窗口,并且我得到了这些有用的构建错误:
<unknown>:0: error: unable to execute command: Segmentation fault: 11
<unknown>:0: error: swift frontend command failed due to signal
我在这里严重得罪了编译器。那么遍历字典数组并找到每个字典的“title”属性的正确方法是什么?
【问题讨论】:
-
不要忽略错误返回,专业要求处理错误路径。
-
println()jsonData,jsonDict,books。将错误变量添加到NSData.dataWithContentsOfFile。如果有错误,请检查返回值和println()任何错误变量。并不是说println()足以处理错误。深入使用调试器也是一个有用的调试过程。
标签: ios arrays json dictionary swift