Evgeniy Kleban
Evgeniy Kleban

Reputation: 6940

Type has no subscript members

I use the SwiftyJson library to help me parse json response.

This code:

Alamofire.request(req).validate().responseJSON { (response) in


    switch response.result{
    case .success(let dataJson):
        let json = JSON(dataJson)

for (key, subJson) in json.enumerated() {
                print("iterate")
                print(key)
                print(subJson)
                subJson["name"]
            }

        case .failure(let error):
            print(error)
        }

Does not work, and yields:

subJson["name"] - Type '(String, JSON)' has no subscript members

However, when I change it to:

 for (key, subJson):(String, JSON) in json {
                print("iterate")
                print(key)
                print(subJson)
                subJson["name"]
            }

It works. But why

for (key, subJson) in json.enumerated() {
                    print("iterate")
                    print(key)
                    print(subJson)
                    subJson["name"]
                }

does the above work?

Upvotes: 1

Views: 1527

Answers (1)

Nirav D
Nirav D

Reputation: 72410

You are looking at wrong side the issue is not with explicit type (String, JSON), when you specify the the explicit type (String, JSON) you have removed the enumerated() if you put the enumerated() also with it you will get error.

for (key, subJson):(String, JSON) in json.enumerated() {

}

(offset: Int, element: (String, JSON))' is not convertible to '(String, JSON)

From Apple Documentation: enumerated()

Returns a sequence of pairs (n, x), where n represents a consecutive integer starting at zero, and x represents an element of the sequence.

Means when you use enumerated() Xcode will consider key as index and subJson as tuple of (String, JSON) so that is the reason you are getting that array. Now you actually don't need to use enumerated here as of when you use for in loop with JSON it will already give you (String, JSON) so use that one.

for (key, subJson) in json {
    print("iterate")
    print(key)
    print(subJson)
    subJson["name"]
}

Upvotes: 2

Related Questions