Null Coalescing in Kotlin and Swift

Sometimes it is desirable to evaluate a nullable expression in an if-else fashion. Both Kotlin and Swift has facility to do son on a single line using operators like ?: in kotlin and ?? in Swift.

Optionals are a powerful source of safety in both Kotlin and Swift, but can also be annoying if you find them littered throughout your code. Nil coalescing operator helps you solve this problem by either unwrapping an optional if it has a value, or providing a default if the optional is empty.

Kotlin

Swift

The expression above returns “Nothing here” if data?.first() or data itself yield a null value else the result of data?.first().