Vlad Alexeev
Vlad Alexeev

Reputation: 2214

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
}

Upvotes: 1

Views: 187

Answers (1)

Eric Aya
Eric Aya

Reputation: 70098

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.

Upvotes: -1

Related Questions