Swift guard vs if-else example

if-else checks for the expression to be true whereas guard statement focuses on performing a function if a condition is false; this allows us to trap errors and perform the error conditions early in our functions which is particularly helpful in case of form validations. It also helps to keep the code more clean and readable.

import UIKit

func checkEmployeeGuard(name: String?, age: Int8?) {
    
    guard let employeeName = name else {
        print("Name not sent")
        return
    }
    
    guard let employeeAge = age else {
        print("Age not sent")
        return
    }
    
    print("Name is \(employeeName), age \(employeeAge)")
    
}

checkEmployeeGuard(name: nil, age: nil)
//result = Name not sent

checkEmployeeGuard(name: "Joe", age: nil)
//result = Age not sent

checkEmployeeGuard(name: "Joe", age: 32)
//result = Name is Joe, age 32


func checkEmployeeIfElse(name: String?, age: Int8?) {
    
    let employeeName = name
    if employeeName == nil {
        print("Name not sent")
        return
    }
    let employeeAge = age
    if employeeAge == nil {
        print("Age not sent")
        return
    }
    
    print("Name is \(employeeName ?? ""), age \(employeeAge ?? 0)")
    
}

checkEmployeeIfElse(name: nil, age: nil)
//result = Name not sent

checkEmployeeIfElse(name: "Joe", age: nil)
//result = Age not sent

checkEmployeeIfElse(name: "Joe", age: 32)
//result = Name is Joe, age 32