Have any Question?

You can ask below or enter what you are looking for!

What is the difference between Guard and If

guard statement is one of three branch statements in Swift, the if statement, guard statement and switch statement.

It is used to transfer program control out of a scope if one or more of its conditions was not met, in others words, it guarantees that all of its conditions are met, otherwise the program will enter the else statement.

How to use guard statement

  • The value of any of the guard conditions must be of type Bool or a type bridged to Bool
  • else statement is required
  • the else clause must call function with Never return type or transfer the program control out of the guard enclosing function using one the following: return, continue, break, throw.
  • Any value assigned to a variable or constant from optional binding in guard statement is available to the enclosing scope of the guard statement

guard statement examples

Using guard statement to check that a condition is met

        let x = 1
        guard x > 0 else {
            // condition not met; x is not greater than zero
            return
        }
        // x is greater than zero

Using guard with optional binding

        //txtFirstName and txtLastName are two IBOutlet UITextFields
        guard let firstName = txtFirstName.text else {
            return
        }
        guard let lastName = txtLastName.textColor else {
            return
        }
        //unlike if statement, firstName and lastName are available to surrounding code
        let fullName = "\(firstName) \(lastName)"
        print(fullName)

Now try the optional binding example using if statement

        if let firstName = txtFirstName.text {
            if let lastName = txtLastName.text {
                let fullName = "\(firstName) \(lastName)"
                print(fullName)
            } else {
                return
            }
        } else {
            return
        }
        // you cannot access firstName and lastName here because they are availalbe
        //only inside the if statement

From the examples above you can see the following advantages of using guard over if statement:

  • It makes your code more readable by transferring program control early if conditions are not met
  • variables and constants created with optional binding in guard statement are available to the code that follows guard statement

Leave a Reply

Your email address will not be published. Required fields are marked *