Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 591
Laurent Avatar asked Jun 16 '15 13:06

Laurent


2 Answers

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.

like image 193
giorashc Avatar answered Oct 21 '22 14:10

giorashc


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.

like image 2
qwerty_so Avatar answered Oct 21 '22 13:10

qwerty_so