When to use Guard in Swift

The Swift guard statement consists of a condition and an else statement. If the condition is false, the else statement is executed. This post presents a number of example use cases where guard can be used in Swift:

  1. Throw Errors with guard
  2. Unwrap Optionals with guard
  3. Verify Requirements and Exit Early with guard
  4. Check OS Version Compatibility with guard

Throw Errors with Guard

Use guard to throw errors in functions that perform validation or potentially failing operations.

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
    }
}

Unwrap Optionals with Guard

Instead of many if let statements, guard 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 for submission
}

Verify Requirements and Exit Early with Guard

Functions and logic in your app may require a specific set of conditions to be met. Use guard to exit early when logical requirements are not met:

class FormViewController: UIViewController {
    var hasEdits = true
    var forceSave = false

    // other functions

    func saveData() {
        guard hasEdits || forceSave else {
            return
        }
    
        // Handle data saving
    }
}

Check OS version compatibility with Guard

Sometimes functionality in your app can only occur on a specific iOS, macOS, or other OS version. You can use guard to check version compatibility inside of a function:

func showTelephotoCamera() throws {
    guard #available(iOS 13, *) else {
        throw CameraError.deviceNotSupported
    }
    
    let cameraController = MyCameraViewController()
    cameraController.camera = .telephoto
    present(cameraController, animated: true, completion: nil)
}

Guard in Swift

That’s it! By using guard in Swift you can throw errors, unwrap options, verify program requirements, and check API availability.