Mark Tyers Mark Tyers - 1 month ago 7
JSON Question

Strange behaviour of optionals in Swift 3

I have experienced a strange behaviour when parsing JSON data using Swift 3.

do {
let json = try JSONSerialization.jsonObject(with: data!, options: []) as! NSDictionary
let items:[AnyObject] = (json["items"] as? [AnyObject])!
for item in items {
let id:String = item["id"] as! String
print("ID: \(id)")
let info = item["volumeInfo"] as AnyObject
print(info)
let title = info["title"]
print(title)
}
} catch {
print("error thrown")
}


This produces the following output. Notice that info is an optional but if I try to unwrap it it states it is not an optional! The script crashes on
let title = info["title"]
As a result I can't access the title key. This behaviour has changed since Swift 2.

ID: lbvUD6LUyV8C
Optional({
publishedDate = 2002;
publisher = "Sams Publishing";
title = "Java Deployment with JNLP and WebStart";
})

Rob Rob
Answer

You can do something like:

do {
    let json = try JSONSerialization.jsonObject(with: data!) as! [String: Any]
    let items = json["items"] as! [[String: Any]]
    for item in items {
        let id = item["id"] as! String
        let info = item["volumeInfo"] as! [String: Any]
        let title = info["title"] as! String

        print(id)
        print(info)
        print(title)
    }
} catch {
    print("error thrown: \(error)")
}

I might suggest excising the code of the ! forced unwrapping (if the JSON was not in the form you expected, do you really want this to crash?), but hopefully this illustrates the basic idea.