What is nil coalescing?

Nil-Coalescing is like an else in 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


  • Article By :
    Founder of DaddyCoding. Studied Computer Science, Information System and Information Technology at BYU-Hawaii. Currently spending most of my time researching and learning on helping to expose making iOS apps.

Random Posts

Leave a Reply

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