尝试查找每本书的标题:
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 limited”弹出窗口,并且我得到了这些有用的构建错误:
<unknown>:0: error: unable to execute command: Segmentation fault: 11
<unknown>:0: error: swift frontend command failed due to signal我在这里严重冒犯了编译器。那么,迭代字典数组并找到每个字典的"title“属性的正确方法是什么呢?
发布于 2014-07-22 05:57:33
你遇到了问题,因为Swift无法推断出book是一个可迭代的类型。如果您知道要进入的数组的类型,则应显式强制转换为此类型。例如,如果数组应该是以字符串作为对象和键的字典数组,则应执行以下操作。
if let books = jsonDict["book"] as? [[String:String]] {
for bookDict in books {
let title = bookDict["title"]
println("title: \(title)")
}
}还要注意,您必须从字符串插值中删除下标字典访问,因为它包含引号。你只需要用两行代码就可以了。
https://stackoverflow.com/questions/24875394
复制相似问题