Swift - iterate an array of dictionaries

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"])")
    //}

When I uncomment these last three lines, all hell breaks in Xcode6 beta3 - all the text turns white, I get constant pop-ups "SourceKitService Terminated" and "Editor temporarily limited", and I get these useful build errors:

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

I seriously insulted the compiler here. So what is the correct way to iterate over an array of dictionaries and find the title property for each dict?

+4
source share
1 answer

, Swift , . , . , , , , .

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

, , . .

+14

All Articles