Concept Flow - Guard for early exit pattern
Start function
Evaluate guard condition
Continue
Rest of [Return or break
The guard statement checks a condition early. If false, it exits the function immediately. Otherwise, the code continues.
func checkAge(age: Int) { guard age >= 18 else { print("Too young") return } print("Welcome") }
| Step | age | guard condition (age >= 18) | Branch taken | Action | Output |
|---|---|---|---|---|---|
| 1 | 16 | False | No (early exit) | Print "Too young" and return | Too young |
| 2 | 20 | True | Yes (continue) | Print "Welcome" | Welcome |
| Variable | Start | After Step 1 | After Step 2 | Final |
|---|---|---|---|---|
| age | input | 16 | 20 | 20 |
guard condition else {
// exit early (return, break)
}
- Checks condition early
- If false, exits function immediately
- Keeps main code less nested
- Used for input validation or safety