Saturday, November 19, 2016

Swift Tip - Using the guard statement

Very often, in your app you need to check if multiple variables are non-nil before you can perform some processing. For example, the following example shows that you can use the if statement to verify that both the credit card no. and expiry date is non-nil before you validate the credit card:

    func validatePayment(creditCardNo:String?, expiry:String?){
        if let cc = creditCardNo {
            if let exp = expiry {
                print("Validating credit card...")
                //...
                return
            }
        }
        print("Missing Credit Card No. or Expiry Date")

    }

However, the nesting of multiple if statements makes your code really unwieldy. A better way is to use the guard statement, like this:

    func validatePayment(creditCardNo:String?, expiry:String?){
        guard let cc = creditCardNo, let exp = expiry
        else {
            print("Missing Credit Card No. or Expiry Date")
            return
        }
        //---validate credit card---
        print("Validating credit card...")

    }

The guard statement ensures that both statements (let cc = creditCardNo and let exp = expiry) are true; else it will execute the else block.

The following shows the output of the function with the following combinations of arguments:

        //---Missing Credit Card No. or Expiry Date---
        validatePayment(creditCardNo: nil, expiry: "11/21")
        validatePayment(creditCardNo: "1234567890123456", expiry: nil)
        validatePayment(creditCardNo: nil, expiry: nil)
        
        //---Validating credit card...---

        validatePayment(creditCardNo: "1234567890123456", expiry: "11/21")

No comments: