"Ambiguous use of subscript" error after Xcode update

After updating to Xcode 7.3 I receive an "Ambiguous use of subscript" error when retrieving JSON but ONLY when I try to build the app on my iPhone and not in the simulator.


This is the line where I receive the error:

guard let item = jsonResult[0] as? [String: AnyObject],


Any ideas why this is happening?


Thanks for your help!

What is the type of variable 'jsonResult'? Is it being bridged from an Obj-C collection type?


The likely problem is that the compiler can't tell whether '[0]' is an array subscript or a dictionary subscript. You're probably going to have to tell it explicitly, either by a variable type annotation or by an explicit cast.

Thank you!


Not sure if this is the correct terminology but I cast the jsonResult as an NSArray (see below) and it worked.

let jsonResult = try NSJSONSerialization.JSONObjectWithData(urlContent, options: NSJSONReadingOptions.MutableContainers) as! NSArray
if jsonResult.count > 0 {
                guard let item = jsonResult[0] as? [String: AnyObject],

Good that you got it working. Just as an FYI though, if that JSON fails to parse into an array, that forced downcast "as!" will crash your app. Unless you're loading the JSON from your app bundle or otherwise creating it in such a way that it cannot possibly be anything other than an array, you'll need to add some error handling.

The JSON request is surrounded by a do-catch. I have tested it by forcing my url request to fail and it seems to catch alright. I just didnt want to write all the code out because theres a number of lines within the do/catch. I am new to Swift and coding in general and I can easily miss things like that so thanks for looking out!

Fair enough. But if it's coming from an external source it could be well-formed JSON that parses without error but whose top-level element is a dictionary, for example. In which case your app would crash. Unlikely but possible.


As a general rule you should be very careful about everywhere you have a forced unwrap "!" in your code. If all possible cases are under your control or an error there would be fatal anyway (e.g. an outlet declared as an IUO - if UIKit doesn't connect your outlets, there are bigger problems than your code can handle 🙂) then ! is fine. But if any external API or user data is involved then you need to be paranoid, in my experience.

I have the same problem ... You can resolv this??

"Ambiguous use of subscript" error after Xcode update
 
 
Q