if and guard in Swift
guard bails early so the happy path stays unindented.
func briefing(windKts: Int) -> String {
// guard exits early and keeps the happy path unindented.
guard windKts > 4 else {
return "Postponed: not enough wind"
}
if windKts > 25 {
return "Small craft advisory: race abandoned"
} else if windKts > 15 {
return "Reef early, \(windKts) kts gusting"
}
return "Fair racing in \(windKts) kts"
}
print(briefing(windKts: 3))
print(briefing(windKts: 18))
print(briefing(windKts: 9))
How it works
guard windKts > 4 else { return ... }handles the bad case first.if/else ifchains handle the graded conditions.- Every path returns a string — the compiler checks.
Keywords and builtins used here
IntStringbriefingelsefuncguardifprintreturn
The run, in numbers
- Lines
- 16
- Characters to type
- 422
- Tokens
- 84
- Three-star pace
- 70 tpm
At the three-star pace of 70 tokens a minute, this run takes about 72 seconds.
Step 1 of 3 in Control flow, step 4 of 27 in Language basics.