user2976267 user2976267 - 4 months ago 18
Swift Question

Cannot subscript a value error when trying to parse JSON

I'm new to SWIFT, going from Android development, and try to parse json as Dictionary but get 'Cannot subscript a value of type '[AnyObject]' with an index of type 'String' at

if let dict = Utils.convertStringToDictionary(response)! as? [String: AnyObject]{

if let response = dict["response"] as? [AnyObject]{

if let first_name = response["first_name"] as? String {//error
NSLog("first_name = \(first_name)")
}
}

}


Just in case, here's the Utils.convertStringToDictionary method :

public static func convertStringToDictionary(text: String) -> [String:AnyObject]? {
if let data = text.dataUsingEncoding(NSUTF8StringEncoding) {
do {
let json = try NSJSONSerialization.JSONObjectWithData(data, options: .MutableContainers) as? [String:AnyObject]
return json
} catch {
NSLog("Something went wrong")
}
}
return nil
}

Answer

With this line:

if let response = dict["response"] as? [AnyObject]

you are casting dict["response"] as an array containing items of type AnyObject.

But then with this line:

if let first_name = response["first_name"] as? String

you are trying to access this array as if it were a dictionary.

That's why the compiler tells you

Cannot subscript a value of type [AnyObject] with an index of type String

because [AnyObject] is an array and you cannot subscript an array with a String like with a dictionary, it only accepts subscripting with an index.

Comments