Python Operators, Range Types & Nil-Coalescing
Swift provides standard arithmetic and logical operators alongside expressive Range types. Learn closed ranges (1...5), half-open ranges (0..<count), one-sided ranges (...5), and the nil-coalescing operator (??) for fallback handling.
"A closed range (1...5) is inclusive like an RSVP list inviting guests 1 through 5. A half-open range (0..<5) is like an index ruler stopping just before 5, matching zero-indexed collection bounds perfectly."
Deep Dive: How It Works
Closed Range (a...b): Includes both a and b (e.g. 1...5 contains 1, 2, 3, 4, 5).
Half-Open Range (a..<b): Includes a up to but excluding b (e.g. 0..<5 contains 0, 1, 2, 3, 4).
Nil-Coalescing (a ?? b): Unwraps optional a if it contains a value, or returns default fallback b if a is nil.
Overflow Operators: Standard arithmetic halts on overflow; use &+, &-, &* if wrapping behavior is explicitly desired.
Syntax Blueprint
let closed = 1...5 let halfOpen = 0..<3 let fallback = optionalVal ?? "default"
Use ... for inclusive ranges, ..< for upper-bound exclusive ranges, and ?? for fallback unwrapping.
Core Rules to Remember



Common Beginner Traps & How to Fix Them
Using 0...array.count for loop iterations.Why it happens: array.count is out-of-bounds for zero-indexed arrays, causing a fatal IndexOutOfBounds runtime crash.
How to fix: Use half-open range 0..<array.count or simply for item in array.
Live Interactive Example
Hit Run Code to see it liveYour Turn: Micro Challenge
No pressure! Edit the starter code below and test your solution with instant feedback.
Calculate Factorial with Closed Range
Declare var factorial = 1.
Use a for-in loop over closed range 1...5 to multiply factorial *= n.
Print "Factorial of 5: \(factorial)".
Finished reading and practicing?
Mark this lesson as completed to update your course progress.