leo0019 leo0019 - 25 days ago 12
JSON Question

The correct JSON comparison with Strings (SWIFT 3)

request( url!, method: .get, parameters: nil)
.responseJSON { response in

print(response.result) // result of response serialization

if let newJSON = response.result.value {
let json = JSON(newJSON)
for (key,subJson):(String, JSON) in json {

let age = subJson["age"]
let name = subJson["name"]
let status = subJson["status"]

//the code below looks kind of confusing if it gets longer

if age == "22"{
if status == "highschool "{
if name == "Leo"{
//do something with the result


Is there a better way of checking if the result from JSON is same as the Strings?

Answer

This is a classic pyramid of doom. There are a few ways to get rid of it and you need to pick an appropriate one according to your context. Basically the ways are:

  • Using early returns and guard statements.
  • Combining multiple if-let statements into one.
  • Using for-where.

Given all above you could rewrite your piece of code into something like this:

request( url!, method: .get, parameters: nil)
    .responseJSON { response in
        print(response.result)   // result of response serialization

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

        let json = JSON(newJSON)

        for (key,subJson):(String, JSON) in json {
            let age = subJson["age"]
            let name = subJson["name"]
            let status = subJson["status"]

            if age == "22" && status == "highschool" && name == "Leo" {
                //do something with the result 
            }
        }
    }