Wednesday, August 29, 2018

Swift Nil-Coalescing Operator for Optionals


Let’s see how to use Coalescing operator for optionals in swift.


     
  var name: String?
  label.text = name ?? ""



Here ?? is the Coalescing operator which  checks whether optional is nil or not.

If Nil, takes default value, If not takes optional.

In short, below is what it does.


     
  if name != nil {
     //use name!
  } else {
     //use default value
  }



Nil-Coalescing Operator is very useful for checking optional and giving default value in a single statement instead of going with optional binding.

     
  if let nameVal = name {
       label.text = nameVal
   } else {
       label.text = “”
   }



We can not use ternary operator for optionals. Below gives a build error.

     
  label.text = name ? name! : “”





Hope this post is useful. Feel free to comment incase of any queries.



No comments:

Post a Comment