繁体   English   中英

Swift - 迭代字典数组

[英]Swift - iterate array of dictionaries

试图找到每本书的标题:

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”和“编辑器功能暂时限制”弹出窗口,我得到这些有用的构建错误:

<unknown>:0: error: unable to execute command: Segmentation fault: 11
<unknown>:0: error: swift frontend command failed due to signal

我在这里严重冒犯了编译器。 那么迭代字典数组并找到每个字典的“标题”属性的正确方法是什么?

你遇到了问题,因为Swift无法推断书籍是一种可迭代的类型。 如果你知道进入的数组的类型,你应该明确地转换为这种类型。 例如,如果数组应该是包含字符串作为对象和键的字典数组,则应执行以下操作。

if let books = jsonDict["book"] as? [[String:String]] {
    for bookDict in books {
        let title = bookDict["title"]
        println("title: \(title)")
    }
}

另请注意,您必须从字符串插值中删除下标字典访问,因为它包含引号。 你只需要在两行上完成。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM