Nil Coalescing in Swift

Nil Coalescing can come in handy when you have to transfer value from an optional to a required (non-optional). Though it can be easily solved using != nil checks and using ternary operator but in swift we have a much graceful option Nil Coalescing. Nil Coalescing provides us with option to return a default value when nil is found.We can simply put the suspected variable/constant in small brackets “()” with default value along with ?? infix. Run the following code in playground

var asBlogOptional:String?

var asBlog:String!

asBlog = (asBlogOptional ?? "hello")// use of coalescing

print(asBlog)// will print hello as asBlogOptional is nil

It will print hello as asBlogOptional is nil at present.Now run the following code in playground

var asBlogOptional:String? = "hi"

var asBlog:String!

asBlog = (asBlogOptional ?? "hello")

print(asBlog) //it will print hi as asBlogOptional has a value now

Now hi is printed as asBlogOptional is not nil and has hi as its value.

 

A pat on the back !!