ADVERTISEMENT
Google AdSense Slot (headerLeaderboard)
Set your Publisher ID in src/config/ads.ts to display live ads.
Swift Tutorial• 6 min read
Control Flow, Range Operators & Exhaustive Switch
Closed ranges ..., half-open ranges ..<, tuple matching, and where clauses
Swift provides control flow with range operators (0...5 and 0..<5) and switch statements that must be 100% exhaustive.
Ranges & Advanced Switch Matching
Closed Range (1...5): Includes 1, 2, 3, 4, and 5.
Half-Open Range (1..<5): Includes 1, 2, 3, 4 (excludes 5), ideal for zero-indexed array counts.
No Fallthrough: Swift switch cases do not fall through to the next case by default, eliminating break statements.
where clauses: Adds conditional logic directly into switch pattern matching.
Pattern Matching with Switch and Ranges
let examScore = 88
let letterGrade: String
switch examScore {
case 90...100:
letterGrade = "A"
case 80..<90:
letterGrade = "B"
case 70..<80:
letterGrade = "C"
default:
letterGrade = "Needs Improvement"
}
print("Final Grade: \(letterGrade)") // Final Grade: BRanges seamlessly map to switch evaluation cases.
ADVERTISEMENT
Google AdSense Slot (inContentBanner)
Set your Publisher ID in src/config/ads.ts to display live ads.
Test Yourself With Exercise
Which range operator in Swift creates a half-open range from `a` up to (but not including) `b`?