Wednesday, April 18, 2018

If-Let & Guard-Let Multiple Optional Bindings


Instead of nesting with multiple optional binding statements using if-let or guard-let, We can use single statement for multiple optional bindings.

Let’s take a sample Employee class which is having both first name and last name as optionals.

If we need to get full name of employee, Let’s see how can we get it using nested and single optional binding statements.

-------------------------------------------------------------------
class Employee {    
    var firstName: String?
    var lastName: String?
    
    var empID: String
    
    init(employeeID: String) {
        self.empID = employeeID
    }
    
}

-------------------------------------------------------------------


let emp = Employee(employeeID: "123")
emp.firstName = "Karunakar"
emp.lastName = "Bandikatla"

var fullName = ""

-------------------------------------------------------------------

#Nested

-------------------------------------------------------------------
if let firstName = emp.firstName {

    if let lastName = emp.lastName {
        fullName = firstName + " " + lastName
    }
}
-------------------------------------------------------------------


#Single If-Let

-------------------------------------------------------------------

if let firstName = emp.firstName, 
   let lastName =  emp.lastName {

    fullName = firstName + " " + lastName
}

-------------------------------------------------------------------


Same way we can write guard-let.

-------------------------------------------------------------------
func getFullName(emp: Employee) -> String {
    
    guard let firstName = emp.firstName, 
             let lastName = emp.lastName else{
        return ""
    }
    
    return firstName + " " + lastName
    
}

fullName = getFullName(emp: emp)
-------------------------------------------------------------------

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




No comments:

Post a Comment