Best practice to find out if SwiftyJSON dictionary has key

tomatentobi picture tomatentobi · Dec 17, 2014 · Viewed 18.2k times · Source

I'm trying to find a way to get the value of a key in a SwiftyJSON dictionary and return a default string, if the key is not set. The following example works fine, but I'm not really satisfied. Do you know a more elegant way?

Example:

let users: JSON = [
    ["id": 1, "name": "one"],
    ["id": 2],
    ["id": 3, "name": "three"]
]
    
for (key: String, user: JSON) in users {      
    println(user.object.objectForKey("name") != nil
        ? user["name"].stringValue
        : "default")
}

Answer

ciauri picture ciauri · Apr 15, 2016

The latest version of SwiftyJSON has the exists() function.

NOTE: Their latest documentation does not reflect the code very well... The actual method is exists()

// Returns boolean

json["name"].exists()