dbrownjave
dbrownjave

Reputation: 477

Use of unresolved identifier 'json' (Swift 3) (Alamofire)

I am receiving the error: Use of unresolved identifier 'json'

from this line: if let data = json["data"] ...

This is the snippet of the code relevant to the error

        // check response & if url request is good then display the results
        if let json = response.result.value! as? [String: Any] {

            print("json: \(json)")
        }

        if let data = json["data"] as? Dictionary<String, AnyObject> {
            if let weather = data["weather"] as? [Dictionary<String, AnyObject>] {
                if let uv = weather[0]["uvIndex"] as? String {
                    if let uvI = Int(uv) {
                        self.uvIndex = uvI
                        print ("UV INDEX = \(uvI)")
                    }
                }
            }
        }

Upvotes: 1

Views: 1647

Answers (1)

nathangitter
nathangitter

Reputation: 9777

You have a scoping issue. The json variable is only accessible within the if let statement.

To solve this, an easy solution is to move the rest of the code inside the braces of the first if let statement:

if let json = response.result.value! as? [String: Any] {
    print("json: \(json)")
    if let data = json["data"] as? Dictionary<String, AnyObject> {
        if let weather = data["weather"] as? [Dictionary<String, AnyObject>] {
            if let uv = weather[0]["uvIndex"] as? String {
                if let uvI = Int(uv) {
                    self.uvIndex = uvI
                    print ("UV INDEX = \(uvI)")
                }
            }
        }
    }
}

As you can see from your code, the nesting is starting to make it difficult to read your code. One way to avoid nesting is to use the guard statement, which keeps the new variable in the outer scope.

guard let json = response.result.value else { return }

// can use the `json` variable here
if let data = json["data"] // etc.

Upvotes: 1

Related Questions