Nil-Coalescing is like an
if statement. It allows you to check if there is a value, and if there is not value, do this. For better explanation, let me show you in code. It’s quite a powerful line of code which prevent your XCode from crashing if you are the type that love force casting.
By applying nil-coalescing, you are saying, “Hey, if there is no value, simply return whatever so my app continues to run and not crash“. Here, we have created number which is empty and anotherNumber which contain 40. We then create newNumber and assign number to it but because we are using
nil coalescing, it will return anotherNumber because number is empty.
var number: Int?
var anotherNumber = 40
var newNumber = number ?? anotherNumber // 40