Coding/Learn/swift/swift operators and ranges
Swift Foundational Course
01.Introduction, Safety Philosophy & The Toolchain
02.Constants (let), Variables (var) & Type Inference
03.Strings, String Interpolation & Multiline Literals
04.Operators, Range Types & Nil-Coalescing
05.Control Flow: If, Switch Pattern Matching & Guard Statements
06.Optionals, Optional Binding & Optional Chaining
07.Arrays, Sets & Higher-Order Collection Operations
08.Dictionaries, Default Lookups & Tuples
09.Loops, Defer Execution & Labeled Statements
10.Functions, Argument Labels & In-Out Parameters
11.Closures, Trailing Closures & Shorthand Arguments
12.Enums, Raw Values & Associated Values (Tagged Unions)
13.Error Handling: Throwing Functions, Do-Catch & Try Options
14.Structures (struct), Value Semantics & Mutating Methods
15.Classes, Reference Semantics & Inheritance
16.Automatic Reference Counting (ARC), Weak & Unowned References
17.Properties: Stored, Computed, Observers (didSet) & Lazy
18.Protocols, Protocol Extensions & POP (Protocol-Oriented Programming)
19.Generics, Type Constraints & Associated Types
20.Capstone: Production Async/Await Cache & JSON API Engine
Course Certificate0%

Complete all lessons to earn

LearnOperators, Range Types & Nil-Coalescing
4 / 20 0%
Lesson 04 of 20
8 mins read

Operators, Range Types & Nil-Coalescing

PreviousNext Lesson
In Plain English

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.

The Mental Model

"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.

PointCore Rules to Remember

Point star
Overflow Protection: Swift prevents silent integer overflow crashes by trapping at runtime unless overflow operators (&+) are used.
Point star
Range Pattern Matching: Ranges integrate directly into switch cases: case 90...100: print("A").
Point star
Nil Coalescing: Short-circuits evaluation: if the left operand is not nil, the right fallback operand is never executed.

Common Beginner Traps & How to Fix Them

Mistake: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.

Pro Tip: Use one-sided ranges like numbers[2...] to slice an array from index 2 to the end.

Live Interactive Example

Hit Run Code to see it live
Range Iteration and Nil-Coalescing Fallback
Swift 5.10 / LLVM
1
2
3
4
5
6
7
8
9
10
11
12
13
Output Console
Click "Run Code" to view the rendered output.
How it works: Nil-coalescing ?? resolved to default port 8080, and range 1...3 summed 1 + 2 + 3 = 6.

Your Turn: Micro Challenge

No pressure! Edit the starter code below and test your solution with instant feedback.

Micro Exercise

Calculate Factorial with Closed Range

  • PointDeclare var factorial = 1.
  • PointUse a for-in loop over closed range 1...5 to multiply factorial *= n.
  • PointPrint "Factorial of 5: \(factorial)".
1
2
3
4
Sandbox Output
Click "Run & Check" to test your solution.

Finished reading and practicing?

Mark this lesson as completed to update your course progress.

PreviousNext Lesson
Overview100 SheetLearnCertificates