Wednesday, September 26, 2018

Swift - Multiple levels of Optional Binding


If there is Optional, We tend to bind them using guard or if let multiple levels which should be based on what we need exactly.

     
  class Person {

    var name: String?
    weak var spouse: Person?
    
      init(name: String) {
          self.name = name
      }

   }

    let wife = Person(name: "Wife")
    let husband = Person(name: "Husband")
    wife.spouse = husband
    husband.spouse = wife

  

I need to display spouse name in a label.

We don’t need two bindings like below.

     
   if let spouse = husband.spouse, 
                   let name = spouse.name {
        lblSpouseName.text = name
   }

  
Cause, We are not using binded spouse(let spouse = husband.spouse) object. We are using only minded spouse name(let name = spouse.name)

As here what we need is only spouse name, We can take help of optional chaining in optional binding.

     
  if let name = husband.spouse?.name {
      lblSpouseName.text = name
  }

  

husband.spouse?.name is optional chaining and gives value only If husband’s spouse is not nil and spouse name is also not nil.

That’s how we need to use binding for the things we need in the scope of If let or guard let.

In the above case, Coalescing operator works like charm and best fit where we can give a default value as well.


     
  lblSpouseName.text = husband.spouse?.name ?? "NA"
    
  

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



1 comment:

  1. Excellent goods from you, man. I’ve understand your stuff previous to and you’re just too excellent. I actually like what you’ve acquired here, certainly like what you are stating and the way in which you say it.
    Mobile App Development Company in Dubai
    Android App Development Company in Dubai

    ReplyDelete