Swift - 迭代字典数组

sol*_*eil 5 arrays json dictionary ios swift

试图找到每本书的标题:

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"])")
    //}
Run Code Online (Sandbox Code Playgroud)

当我取消注释最后三行时,Xcode6 beta3中的所有内容都会崩溃 - 所有文本都变为白色,我得到常量"SourceKitService Terminated"和"编辑器功能暂时限制"弹出窗口,我得到这些有用的构建错误:

<unknown>:0: error: unable to execute command: Segmentation fault: 11
<unknown>:0: error: swift frontend command failed due to signal
Run Code Online (Sandbox Code Playgroud)

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

Mic*_*lum 14

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

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

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

  • 如果它对其他人有帮助,[[String:String]]位说"书籍(可能)是一个字典数组,其中键和值都是字符串"或者这种格式对我来说比较熟悉:Array <Dictionary <字符串,字符串>> (3认同)