1
votes

Initially I had this code in Swift 2.1

func onSuccess(jsonData: AnyObject?){
    print(jsonData["message"]) 
}

After I upgraded to Swift 2.2 , I got an error such as

Ambiguous reference to 'subscript'

for the line print(jsonData["message"])

I changed my code to this

func onSuccess(jsonData: AnyObject?) {

        let json = (jsonData as? [String:AnyObject?]) ?? ["":""]
        print(json)
}

However this statement is always failing because AnyObject? to [String:AnyObject?] type casting is not happening and getting the nil coalescing value. I want to type cast from AnyObject? to [String:AnyObject]. Is it possible?

2
post your JSON structure - Venk
The type [String:AnyObject?] does not exist at all since by definition all keys and values of a dictionary are required to be non-optional types. - vadian

2 Answers

1
votes

You are getting Ambiguous reference to 'subscript' because of your jsonData["message"] in the Swift 2.2 you should use objectForKey instead of ["key"]. In your case you should write your code like this jsonData.objectForKey("message") thats the your first question.

Your second question answer is Are you sure your JSON Data is a dictionary ? I think your data is an array of dictionaries. If i am right. You should cast your jsonData to array of dictionaries like this;

if let json = jsonData as? [[String:AnyObject?]] {
    for data in jsonData { // Enumerate the array of dicts to get value.
        print(data.objectForKey("message"))
    }
}
3
votes

You could simply use optional binding like this:

func onSuccess(jsonData: AnyObject?) {
    if let json = jsonData as? [String:AnyObject] {
        print(json["message"])
    }
}

There's no good reason to declare the dictionary value as an Optional like [String:AnyObject?] since Swift dictionaries always return Optionals anyway.

This example was for decoding a dictionary.

Now if your jsonData is not a dictionary but, say, an array of dictionaries, you just adapt the type:

func onSuccess(jsonData: AnyObject?) {
    if let json = jsonData as? [[String:AnyObject]] {
        for object in json {
            print(object["message"])
        }
    }
}

Etc.