Swift Guard Statement

In Swift, guard statement is used for early exit from a code block if a certain condition is not met. It is a useful alternative to if statements when validating input data or checking certain conditions that must be met before executing the rest of the code. If the condition in the guard statement is not satisfied, the code execution stops and the program continues from the else block, or throws an error, if specified.

The basic syntax of the guard statement is as follows:

1guard condition else { 2 // statements to execute if the condition is not met 3 return // or throw an error 4} 5// statements to execute if the condition is met

The condition is an expression that returns a Boolean value, which can be a comparison operator, a logical operator, or any other expression that can be evaluated to true or false.

Here is an example of using the guard statement to check if an optional value is not nil and has a specific value:

1func greet(name: String?) { 2 guard let name = name else { 3 print("Name is missing") 4 return 5 } 6 print("Hello, \(name)!") 7} 8 9greet(name: "William") // Output: Hello, William! 10greet(name: nil) // Output: Name is missing

In this example, the name parameter is an optional value. If the value of name is nil, the guard statement executes the statements inside the else block and returns from the function. If the value of name is not nil, the guard statement unwraps it using let binding and assigns it to a constant name that can be used inside the function.

guard with catch

The guard statement can also be used to validate input data and throw an error if the data is invalid:

1enum ValidationError: Error { 2 case emptyName 3 case invalidAge 4} 5 6func register(name: String, age: Int) throws { 7 guard !name.isEmpty else { 8 throw ValidationError.emptyName 9 } 10 guard age >= 18 else { 11 throw ValidationError.invalidAge 12 } 13 // perform registration 14 print("Registration successful") 15} 16 17do { 18 try register(name: "William", age: 25) // Output: Registration successful 19 try register(name: "", age: 20) // throws ValidationError.emptyName 20 try register(name: "Col", age: 16) // throws ValidationError.invalidAge 21} catch let error { 22 print(error) 23}

In this example, the register function validates the input parameters name and age using two guard statements. If the name parameter is an empty string, the function throws an error of type ValidationError.emptyName. If the age parameter is less than 18, the function throws an error of type ValidationError.invalidAge. If both parameters are valid, the function performs the registration and prints a success message.

In the do-catch block, we call the register function with three different sets of input parameters. The first call is successful and prints the success message. The second call throws an error of type ValidationError.emptyName because the name parameter is an empty string. The third call throws an error of type ValidationError.invalidAge because the age parameter is less than 18. The error is caught by the catch block and printed to the console.

The guard statement is a useful tool for early exit from a code block and can help to write more readable and error-resistant code.