Using the guard Statement

Safety is crucial in most modern programming languages because programs that allow the wrong types of data will likely fail or crash the program completely. That’s why real-time avionics programs that control jet airliners rely on safe programming languages like Ada.

Swift emphasizes safety as well, and one feature that Swift offers is called the guard statement. The basic structure of the guard statement looks like this:

guard (condition) else {
// do something here

The guard statement looks to make sure a condition is true. If the condition is false, then exit out of a function without running any code.

By placing a guard statement at the beginning of a function, you can check to make sure all data is valid before running any code. A simple example of a guard statement might look like this, which you can paste and run in a Swift playground:

import Cocoa

func testGuard (myNumber: Int) {
    guard (myNumber % 2) == 0 else {
        print ("Odd number")
    print ("Even number")

testGuard (myNumber: 4)
testGuard (myNumber: 5)

This code checks to see if a number (stored in the myNumber variable), passed into a function, is an odd or even number. If it’s even, then the guard statement lets any code following run. If the number is odd, then the guard statement runs and the return command stops any further code from running in that function.

When you pass the number 4 into the testGuard function, the guard statement lets it run the testGuard code, which prints “Even number”. When you pass the number 5 into the testGuard function, the guard statement catches it, prints “Odd number”, and then exits out of the function.

By placing a guard statement at the beginning of each function, you can make sure that function only receives valid data. By using the guard statement, you can make your code more reliably.

May 15th, 2017 by
HTML Snippets Powered By :