The Swift guard statement consists of a condition and an else statement. If the condition is false, the else statement is executed and the else statement must exit the scope (often using return or throw). This post presents an overview of Swift guard and the most common examples for the guard keyword:
- Swift Guard Keyword
- Guard Else Throw
- Guard Let Optional
- Guard Available
- Guard Multiple Conditions
- Guard Case Enum
Swift Guard Keyword
The multiple use cases for the Swift guard keyword can be grouped into three main categories:
- Exit Early. Like the Guard Let Optional example, a guard statement can be used to exit early if an expected variable is an optional.
- Validate Requirements. Like the Guard Else Throw example, a guard statement can be used to throw an
Errorif an expectation is not met. - Segment Logic. Like in the Guard Available example, a guard statement can be used to perform different logic based on a condition like the current iOS version.
Check out the Swift guard examples in this post to see how the guard keyword can be used exit early, validate requirements, and segment logic.
Guard Else Throw
Use a guard else throw statement to throw errors in functions that perform validation or contain logic that may fail:
enum ValidationError: Error {
case fullNameIsRequired
case lastNameIsRequired
}
func validate(name: String) throws {
guard name.count > 3 else {
throw ValidationError.fullNameIsRequired
}
guard name.contains(" ") else {
throw ValidationError.lastNameIsRequired
}
}
Guard Let Optional
Instead of many if let statements, a guard let optional statement can be used to unwrap optionals and nested optionals:
func submitForm() {
// Unwraps two options with one guard statement,
// nameTextField and the String? text on nameTextField
guard let name = nameTextField?.text else {
return
}
// Handle form submission using the name variable
}
Guard Multiple Conditions
Functions and logic in your app may require a specific set of conditions to be met. A guard with multiple conditions can be used to verify requirements and exit early when logical requirements are not met. To create a guard statement with multiple conditions, separate each condition with a ,:
class FormViewController: UIViewController {
var hasEdits = true
var forceSave = false
// other functions
func saveData(data: Data?) {
// A guard statement with two conditions
guard let data = data, hasEdits || forceSave else {
return
}
// Handle data saving
}
}
Guard Available
Sometimes functionality in your app can only occur on a specific iOS, macOS, or other OS version. You can use guard #available statement to check OS version compatibility:
func showTelephotoCamera() throws {
guard #available(iOS 13, *) else {
throw CameraError.deviceNotSupported
}
let cameraController = MyCameraViewController()
cameraController.camera = .telephoto
present(
cameraController,
animated: true,
completion: nil
)
}
Guard Case Enum
To use a guard statement with an Enum condition, use the case keyword to create a guard case statement:
enum State {
case initial
case active
case done
}
var state = State.active
guard case state = State.initial else {
// Handle unexpected state
}
// Continue execution
Swift Guard Statement
That’s it! By using guard in Swift you can throw errors, unwrap options, verify program requirements, and check API availability.