Kahsn Kahsn - 4 years ago 142
Swift Question

replacing nil value with other customized value

I am using a keychain wrapper written in Swift.
When value is nil, this wrapper I'm using automatically saves data as "nil" instead of saving as an actual nil value.

For ex, ["last_name" : "nil"].


In one of my label in my iOS app, I'm returning last_name value.
It bothers me that a text in label is saying "nil" when there supposed to be nothing.

I remember in Swift that there is a syntax like A ?? B which puts B instead if A is not valid. But I cannot remember it right now.
In my app, I want to something like below:

if the value I'm looking for is nil, then input "" instead of "nil"
If keychain["last_name"] == nil ?? ""


I know this is a horrible explanation but this is all I could come up with.

Answer Source

?? is the nil coalescing operator. It is used for unwrapping optionals — a ?? b is shorthand for a != nil ? a! : b.

You probably want to use the ternary operator instead. You could even combine them like this:

let lastName = keychain["last_name"] == "nil" ? "" : (keychain["last_name"] ?? "")

That said, it might be easier to just filter out these responses immediately after getting the keychain instead of checking every time:

var keychain = ["first_name" : "aaron", "last_name" : "nil"]

keychain.forEach { if $0.1 == "nil" { keychain.removeValueForKey($0.0) } }

print(keychain)  //["first_name": "aaron"]

The $0 is a shorthand argument name. Here's the long form version of the same code:

keychain.forEach { (key, value) -> () in
    if value == "nil" {
        keychain.removeValueForKey(key)
    }
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download