Correctly Parsing JSON in Swift 3

前端 未结 9 971
甜味超标
甜味超标 2020-11-21 07:00

I\'m trying to fetch a JSON response and store the results in a variable. I\'ve had versions of this code work in previous releases of Swift, until the GM version of Xcode 8

9条回答
  •  遥遥无期
    2020-11-21 07:36

    A big change that happened with Xcode 8 Beta 6 for Swift 3 was that id now imports as Any rather than AnyObject.

    This means that parsedData is returned as a dictionary of most likely with the type [Any:Any]. Without using a debugger I could not tell you exactly what your cast to NSDictionary will do but the error you are seeing is because dict!["currently"]! has type Any

    So, how do you solve this? From the way you've referenced it, I assume dict!["currently"]! is a dictionary and so you have many options:

    First you could do something like this:

    let currentConditionsDictionary: [String: AnyObject] = dict!["currently"]! as! [String: AnyObject]  
    

    This will give you a dictionary object that you can then query for values and so you can get your temperature like this:

    let currentTemperatureF = currentConditionsDictionary["temperature"] as! Double
    

    Or if you would prefer you can do it in line:

    let currentTemperatureF = (dict!["currently"]! as! [String: AnyObject])["temperature"]! as! Double
    

    Hopefully this helps, I'm afraid I have not had time to write a sample app to test it.

    One final note: the easiest thing to do, might be to simply cast the JSON payload into [String: AnyObject] right at the start.

    let parsedData = try JSONSerialization.jsonObject(with: data as Data, options: .allowFragments) as! Dictionary
    

提交回复
热议问题