grabury grabury - 1 month ago 63
Swift Question

How to resolve the error "ambiguous reference to member 'subscript'"

I get the error:


Ambiguous reference to member 'subscript'


On the following code:

let jsonObject = try JSONSerialization.jsonObject(with: data, options: [])
guard let jsonDictionary = jsonObject as? [NSObject: AnyObject],
let photos = jsonDictionary["photos"] as? [String: AnyObject], // this line is giving the error
let photosArray = photos["photo"] as [[String: AnyObject]] else {
print("Error")
}


Previous posts have suggested that I change the type from
[String: AnyObject]
to
[AnyObjectHashable: Any]
. This hasn't fixed the error. Can someone explain why this error is occurring and how it can be resolved?

Answer

You can replace this, for making dictionary in swift 3 you can use like [String: Any] instead of [String: AnyObject]

let jsonObject = try JSONSerialization.jsonObject(with: data, options: [])
guard   let jsonDictionary = jsonObject as? [String: Any],
    let photos = jsonDictionary["photos"] as? [String: AnyObject], // this line is giving the error
    let photosArray = photos["photo"] as? [[String: Any]] else {
        print("Error")
}
print(jsonDictionary)