Swift-迭代字典数组 [英] Swift - iterate array of dictionaries

查看:94
本文介绍了Swift-迭代字典数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

试图找到每本书的书名:

Trying to find the title of each book:

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暂时性受限"的弹出窗口,并且得到以下有用的构建错误:

When I uncomment those last three lines, all hell breaks loose in Xcode6 beta3 - all text turns white, I get constant "SourceKitService Terminated" and "Editor functionality temporarily limited" popups, and I get these helpful build errors:

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

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

I have seriously offended the compiler here. So what is the correct way to iterate through the array of dictionaries and find the "title" property of each dict?

推荐答案

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

You're having issues because Swift is unable to infer that books is an iterable type. If you know the type of the array going in, you should be explicitly casting to this type. If for example, the array should be an array of dictionaries which have strings as objects and keys, you should do the following.

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

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

Also note that you have to remove the subscript dictionary access from the string interpolation because it contains quotation marks. You just have to do it on two lines.

这篇关于Swift-迭代字典数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆