Thomas Charlesworth
Thomas Charlesworth

Reputation: 1839

Check if JSON object null swift 3

I'm having a hard time checking if this JSON object is null. Example JSONs with and without customer key.

This is what finalValue equals =

With customer key:

{
  "customer" : { 
      "href" : "myURL"
  },
  "token": "781hjasf98123bjwef8"
}

without customer key:

{ 
    "error" : {
        "message" : "Unauthorized"
    }
}

This is how I try to check, but it always goes to else statement.

            if let value = response.result.value{
                let finalValue = JSON(value)
                if finalValue["customer"] is NSNull{
                    print("if part")
                }else{
                    print("Else part")
                }
            }

Upvotes: 1

Views: 2659

Answers (2)

Hitesh
Hitesh

Reputation: 896

Swift 3.0

Using SwiftyJSON, there is function exists() for checking key is exist or not.

if let value = response.result.value {
        let finalValue = JSON(value)
        if finalValue["customer"].exists() {
            print("if value exists then this part will be executed")
        } else {
            print("if value no longer then this part will be executed")
        }
 }

Without SwiftyJSON

if let value = response.result.value {
        if dictionary.index(forKey: "customer") != nil {
            print("if value exists then this part will be executed")
        } else {
            print("if value no longer then this part will be executed")
        }
 }

Upvotes: 0

Massimo Polimeni
Massimo Polimeni

Reputation: 4906

You can just use optional chaining:

if let finalValue = finalValue["customer"] as? String {
    // there's a value!
}

Upvotes: 2

Related Questions