Swift - iterate array of dictionaries

后端 未结 1 1002
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-01-13 08:50

Trying to find the title of each book:

var error: NSError?
    let path = NSBundle.mainBundle().pathForResource(\"books\", ofType: \"json\")
    let jsonData         


        
1条回答
  •  一整个雨季
    2021-01-13 09:04

    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.

    0 讨论(0)
提交回复
热议问题