Default values for optionals in Swift using the ?? operator

Swift 3

We know we need to test optionals to see if they have a value before we use them. If you use a nil value in your app, you could cause a crash. Let’s look at that.

Potential crash

We want to get a String value from UserDefaults. At this point, we have no idea what the value is, or indeed if it was ever set. On first run of an app, for example, it would never have been set and have a value of nil. Usually, the best way of dealing with this is to unwrap the optional and test the value with an if statement.

This is safe. It will only print the setting1 value if it existed. But what if we wanted to do something with setting1 even if the value didn’t exist? We could use an else statement to provide a default value.

Providing a default value for an optional

That’s a lot of code for providing a default. This is where a Nil-Coalesing Operator can help us. The Nil-Coalesing operator, ie: ??, will unwrap an optional, use it if it has a value, or use the right hand value if it finds nil.

Using ??

Great. If there is a value, it will use it, and we can provide a default value if setting1 equates to nil.

A few rules to using ??. The left hand value, ie: settings1, has to be an optional. The right hand value, must be of the same Type, in our case a String. It’s not costly to use this, because if the left hand value is found, it will not evaluate the right hand value at all.

Conclusion

The Nil-Coalesing Operator allows us to provide a default value for an optional at the time of use, and it is easy to read this short-hand method of doing so.

Leave a Reply

Your email address will not be published. Required fields are marked *