Like a if
statement, guard
execution depends on the Boolean value of an expression. We can use guard
statements to require that the condition must be true when the guard
code is executed after the statement. Unlike if
statements, a guard
statement always has a else
clause that executes the else
code in the substation if the condition is not true.
Func Greet (person: [string:string]) { guard-let name = person["name"] else { return } print ("Hello \ (n AME) ") guard Let location = person[' Location '] else { print (" I hope the weather is nice near you. ") Return } print ("I hope the weather is nice in \ (location).")} Greet (["Name": "John"])//prints "Hello john!" Prints "I hope the weather is nice near you." Greet (["Name": "Jane", "Location": "Cupertino"])//prints "Hello jane!" Prints "I hope the weather is nice in Cupertino."
If guard
the condition of the statement is met, the code continues to execute after the enclosing curly brace of the protection statement ends. Any variable or constant that uses an optional binding as part of the condition and is assigned a value is available for the code snippet that appears for the remaining protection statements.
If the condition is not met, the code on the else
branch will be executed. This branch must transfer control to exit guard
the code snippet that appears in the statement. It can be used to control the transfer of statements such as return
, break
or continue
do this, or it calls a method or function that does not return, for example fatalError()
.
if
using statements on demand guard
improves the reliability of our code compared to statements that can implement the same functionality. It allows your code to be executed coherently without having to wrap it in a else
block, which allows you to handle code that violates the requirements close to the requirements.
Swift Learning notes-control flow-early exit (guard)