Astrid
Astrid

Reputation: 1312

Swift Dictionary confusion

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.

Upvotes: 5

Views: 105

Answers (2)

qwerty_so
qwerty_so

Reputation: 36295

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.

Upvotes: 2

giorashc
giorashc

Reputation: 13713

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.

Upvotes: 3

Related Questions