swiftif-statementswift2guard-statement

How to use guard in swift instead of if


How to use 'guard' in swift.I have gone through many articles about 'guard'.But i didnt get clear idea about this.Please give me clear idea.Please give me sample output for following 'if' statement.

if firstName != "" 
{
   if lastName != "" 
   {
      if address != "" 
      {
        // do great code
      }
   }
 }

Solution

  • you can use guard as well and your code will be more readable

    let firstName = "First"
    let lastName = "Last"
    let address = "" // empty
    
    if firstName != ""
    {
        if lastName != ""
        {
            if address != ""
            {
                print(1,firstName,lastName, address)
            } else {
                print(1,"address is empty")
            }
        } else {
            print(1,"lastName is empty")
        }
    } else {
        print(1,"firstName is empty")
    }
    
    func foo(firstName: String, lastName: String, address: String) {
        guard !firstName.isEmpty else { print(2,"firstName is empty"); return }
        guard !lastName.isEmpty else { print(2,"lastName is empty"); return }
        guard !address.isEmpty else { print(2,"address is empty"); return }
    
        print(2,firstName,lastName, address)
    }
    
    foo(firstName, lastName: lastName, address: address)
    /*
     1 address is empty
     2 address is empty
     */
    foo(firstName, lastName: lastName, address: "Address")
    /*
     2 First Last Address
     */