Swift Coalescing Operator

Johan Attali bio photo By Johan Attali

This is by far one of the best features recently added in the latest XCode 6 Beta 5 build.

This so called coalescing operator is simply defined as:

func ??<T>(optional: T?, defaultValue: @autoclosure () -> T) -> T

It takes an optional as first input and and a default value of the same type as second argument. It returns the first one if it's non nil and the second one if it is.

That means all your old code of the form:

var myStr:String?
var otherVar:MyClass = MyClass()
if let value = myVar {
    otherVar.value = value
else {
    otherVar.value = "defaultValue"

now becomes:

let otherVar.value = myStr ?? "default value"

Really liking where Apple is going with Swift.