Nil-Coalescing Operator

Hi folks, today I’m gonna show you a pretty simple trick to manage optionals, in order to get a default value when unwrapping.

The problem

  • Unwrapping process is a little bit confusing.
  • You must to write many lines in order to assign a default value to a variable.

Before

var quantityStock: Int? = nil
var defaultQuantity: Int = 1

var Total = 0

if age != nil {
Total = quantityStock!
} else {
Total = defaultQuantity
}
print(defaultQuantity) // Total is 1

After

var quantityStock: Int? = nil
var defaultQuantity: Int = 0
var total = quantityStock ?? defaultQuantity // Total is 1
If quantityStock is “nil” assign to Total the defaultQuantity value.

This is calling “Nil-Coalescing Operator”, It’s the way you can make a short conditional using Optionals.

That’s all folks!

If you like it, don’t forget recommend it.