Guard Statement in Swift
In Swift, guard
is a control flow statement used for early exit from a block of code if a certain condition is not met. It helps improve code readability by reducing the nesting levels compared to using if-else
statements for error handling and conditional checks.
guard
provides a way to gracefully exit a scope if conditions are not met.The basic syntax of guard
is as follows:
guard condition else {
// statements to execute if condition is not met
// this block must exit the current scope
}
Here's how guard in Swift works:
- If the
condition
evaluates totrue
, the code execution continues normally after theguard
statement. - If the
condition
evaluates tofalse
, the code inside theelse
block is executed. - The code inside the
else
block must contain statements that transfer control flow out of the current scope, such asreturn
,throw
,continue
, orbreak
. This ensures that the code after theguard
statement can only be executed when the condition is met.
For example, in the context of error handling:
func process(number: Int?) {
guard let number = number else {
print("Error: Missing number")
return
}
// Use 'number' safely here
print("Number is \(number)")
}
process(number: 10) // Output: Number is 10
process(number: nil) // Output: Error: Missing number
In the above example, the guard
statement ensures that the function process
can only proceed if a non-nil value is provided for number
. If number
is nil
, the guard
statement's else
block is executed, printing an error message, and then the function exits early with return
, preventing further execution of the code in the function.
Here's another example:
func greet(person: String?) {
guard let name = person else {
print("No person to greet!")
return
}
print("Hello, \(name)!")
}
// Example usage:
greet(person: "Alice") // Prints: Hello, Alice!
greet(person: nil) // Prints: No person to greet!
In the above example:
- The
greet
function takes an optionalString
parameterperson
. - The
guard let name = person else { ... }
statement unwraps the optionalperson
. Ifperson
isnil
, theguard
block is executed, which prints a message and returns from the function. - If
person
is notnil
, the code after theguard
statement continues to execute, and the function greets the person by printing a message.
In essence, guard
provides a way to ensure that the function's requirements for the input are met, and if not, it bails out early with an error. guard
statements are often used to handle optional unwrapping.