Ambiguous use of xcode 7.1 index

I have this code:

var jsonResult = (try! NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers)) as! NSDictionary var count = jsonResult["levels"]!.count as Int for var i=0; i<count; ++i { let obj = jsonResult["levels"]![i] as! NSDictionary ... } 

In the last line, I get this error:

Ambiguous use of the index

How can i solve this?

This code worked for a while, but with the upgrade to xcode 7.1 it broke and stopped working.

+5
source share
2 answers

You must tell the compiler that the intermediate object is on the line

 let obj = jsonResult["levels"]![i] as! NSDictionary 

After approval jsonResult["levels"]! the compiler does not know what object it is dealing with. You should say this is an NSArray or something else:

 let obj = (jsonResult["levels"] as! NSArray)[i] as! NSDictionary 

Of course, you must additionally make sure that you can really do all this casting and that the objects inside json are really the expected type.


Even a little shorter using just one cast, directly using an NSDictionary array:

 let obj = (jsonResult["levels"] as! [NSDictionary])[i] 

The rationale remains unchanged: you tell the compiler what kind of jsonResult["levels"] . It should be an array containing NSDictionary s.

+19
source

In the new Swift update. You should get your value using the objectForKey("yourKey") method, not ["yourKey"] . In your case

 let obj = jsonResult.objectForKey("levels")![i] as! NSDictionary 
0
source

Source: https://habr.com/ru/post/1235457/


All Articles