swift

The first thing that leaps into the eye by reading the definition of the guard statement is its similarity to if statement.

It is described in a few lines under the heading "Early Exit". In its description it is said that the code following the guard statement is executed only if the declared condition is true, otherwise the other block is executed, that unlike the if statement is mandatory.

The question that is spontaneous is: what is the real difference compared to if, why do I need guard? The answer is not in the manual description but in the title: Early Exit. The usefulness of going out in advance from a procedure is perceived in the optional binding.

This syntax is used to see if an optional variable exists to perform operations on it. Suppose we have a serial device from which we are receiving text strings. Strings are placed in a special variable that must be optional because the end of the procedure does not say that a string has been received, is the case as example, when the device have been disconnected in the meantime. I represent this situation in the code below:

enum ListOfErrors: Error {

    case noError

    case rxError

    case txError

}

 

var rs232: String?

rs232 = "string from external device"

 

if let serial = rs232 {

    print("working on \(serial)")

} else {

    throwListOfErrors.rxError

}

 

guard rs232 != nil else {

    throw ListOfErrors.rxError

}

print("working on \(rs232)")

 

The optional variable rs232 is the string we receive from the external device that in the example is written by hands.

The following code is the example of generating a receive error using first the if statement then guard, with only one error case, as in the example, you might find no particular look more effective than if, but suppose to have to check a number of possible alarms and to act only if all the alarms verified fail; in this case, the code would be much slimmer, easier to read, and faster in execution, in fact, at the first verified condition with the guard not satisfied, the program would stop by generating an error.