Skip to Content
Course content

63: Working with Ranges

Click on the "Edit" button in the top corner of the screen to edit your slide content.

I remember a junior dev on my team who spent an entire afternoon fighting a "fencepost error"—that classic off-by-one bug—while implementing a photo gallery. He was manually incrementing counters and subtracting one from array indices to avoid crashes, but the logic became a tangled mess of +1 and -1. The app would work perfectly for the first nine photos, then crash the moment it hit the tenth. It was a textbook example of trying to manage boundaries by hand when the language provides a much more elegant tool: Ranges.

Inclusive vs. Exclusive Boundaries

In Swift, the most common range you'll encounter is the Closed Range. You create this using the ... operator. If you write 1...5, you're telling Swift you want every integer from 1 to 5, including 5. This is great for things like page numbers in a book or a set of levels in a game where the upper bound is a valid value.

let pages = 1...5
for page in pages {
    print("Loading page \(page)") 
}
// This prints 1, 2, 3, 4, 5

But here is where that junior dev got tripped up: arrays. Because Swift arrays are zero-indexed, the last valid index is always count - 1. If you use a closed range to iterate over an array, you'll almost certainly trigger an "index out of range" crash. That's why we have the Half-Open Range operator, ..<.

let colors = ["Red", "Green", "Blue"]
for index in 0..

I always tell people to default to ..< when dealing with collections. It just maps more naturally to how computer memory is structured.

Handling Open-Ended Limits

Sometimes, you don't actually know where the range ends—or you don't care. You might only care that a value is "at least 18" or "no more than 100." Swift handles this with one-sided ranges. You simply omit one of the numbers.

let upperLimit = ...100
let lowerLimit = 18...

let userAge = 25
if lowerLimit.contains(userAge) {
    print("Access granted.")
}

The contains() method is where ranges really shine. Instead of writing a clunky if userAge >= 18 statement, using a range makes the intent of your code immediately obvious to anyone reading it. It turns a mathematical comparison into a logical "category" check.

Slicing Collections with Ranges

Beyond just loops and checks, ranges are the primary way we "slice" data in Swift. If you have a long list of items and you only want a specific chunk, you can pass a range directly into the array's subscript.

let alphabet = ["A", "B", "C", "D", "E", "F"]
let firstThree = alphabet[0...2] 
// ["A", "B", "C"]

One thing to keep in mind: when you slice an array, Swift doesn't actually create a brand new array. It creates an ArraySlice. It's a high-performance view into the original array. If you need it to be a standard Array again, you'll have to wrap it in Array(), but for most read-only operations, the slice is exactly what you want.




📋 Practical Task

Build a Product Price Categorizer

Imagine you are building an e-commerce dashboard. You need to categorize products based on their price into three tiers: "Budget" (up to $50), "Mid-Range" ($51 to $150), and "Luxury" (over $150). Instead of using multiple if/else comparisons, use Swift Ranges and the contains() method to solve this.

Requirements:

  • Create a variable productPrice with a Double value.
  • Define three ranges: one for budget, one for mid-range, and one for luxury.
  • Use a switch statement or if/else blocks combined with .contains() to print the correct category based on the price.
  • Ensure that a price of exactly $50 falls into "Budget" and $150 falls into "Mid-Range".
// Start your code here
let productPrice = 125.50

// Define your ranges and logic...
Rating
0 0

There are no comments for now.

to be the first to leave a comment.