Swift has a neat, little data type called an Optional. This data type either has a value wrapped inside its’ container or it doesn’t. If it doesn’t, the Optional is equal to nil. You use this data type when there is a possibility of your variable not having a stored value.
The cool bit of code for today is a shorthand operator to use with Optionals. Take the following code for example:
var localSpeedLimit: Int?
let speedLimit: Int
let defaultSpeedLimit = 35
if localSpeedLimit != nil {
speedLimit = localSpeedLimit!
} else {
speedLimit = defaultSpeedLimit
}
This can be shortened by using the Ternary Conditional Operator:
var localSpeedLimit: Int?
let defaultSpeedLimit = 35
let speedLimit = localSpeedLimit != nil ? localSpeedLimit! : defaultSpeedLimit
And then we can shorten it even further using the Nil-Coalescing Operator:
var localSpeedLimit: Int?
let defaultSpeedLimit = 35
let speedLimit = (localSpeedLimit ?? defaultSpeedLimit)
Look how much cleaner it looks!