Swift Dictionary confusion

124 Views Asked by At

Say I have

var dict = parseJSON(getJSON(url)) // This results in an NSDictionary

Why is

let a = dict["list"]![1]! as NSDictionary
let b = a["temp"]!["min"]! as Float

allowed, and this:

let b = dict["list"]![1]!["temp"]!["min"]! as Float

results in an error:

Type 'String' does not conform to protocol 'NSCopying'

Please explain why this happens, note that I'm new to Swift and have no experience.

2

There are 2 best solutions below

0
On BEST ANSWER

dict["list"]![1]! returns an object that is not known yet (AnyObject) and without the proper cast the compiler cannot know that the returned object is a dictionary

In your first example you properly cast the returned value to a dictionary and only then you can extract the value you expect.

0
On

To amend the answer from @giorashc: use explicit casting like

let b = (dict["list"]![1]! as NSDictionary)["temp"]!["min"]! as Float

But splitting it is better readable in those cases.