Swift if value is nil set default value instead

you can do like this but your strValue should be optional type

let strValue:String?
textfield.stringValue = strValue ?? "your default value here"

Using nil-coaleasing operator, we can avoid code to unwrap and clean our code.

To provide simple default value when an optional is nil :

let name : String? = "My name"
let namevalue = name ?? "No name"
print(namevalue)

Important thing to note here is that you don't need to unwrap it using if let or guard here and it will be implicitly unwrapped but safely.

Also it is useful to make your code much cleaner and short :

   do {
        let text = try String(contentsOf: fileURL, encoding: .utf8)
    }
    catch {print("error")}

Above code can be written as :

let text = (try? String(contentsOf: fileURL, encoding: .utf8)) ?? "Error reading file"

The ?? is the nil-coalescing operator, and took me a bit to understand, too. It is a useful tool for simplifying code though. A simple explanation of it is "unless that's nil, then this" so a ?? b returns a if it has a value and b if it doesn't. You can chain them together and return the first non-nil value. Example, a ?? b ?? c ?? d ?? e returns the first non-nil value, or e if they are all nil before it.

Nil-Coalescing Operator

Tags:

Swift