11 Great Uses for Swift Range Operators

When you work with a set of numbers, you want to keep things clean by writing the minimal code possible. Ranges are your super shortcut to working with multiple number values. With the simple >< symbols, you can do a lot of work without much space required.

11. Easy Number Array Creation

Creating an array full of numbers in a row is fast.

let numberArray = [Int](1...5)
//[1, 2, 3, 4, 5]

10. Access Multiple Array Elements

Let’s say you have an array and only want the first 3 elements.

let redThings = ["strawberry", "apple", "ruby", "lipstick", "heart", "lobster"]
print (redThings[0...2])
//["strawberry", "apple", "ruby"]

//Make it even shorter using a one-sided range dropping the 0.
print (redThings[...2])
//["strawberry", "apple", "ruby"]

//Start from an index and go to the end
print (redThings[3...])
//["lipstick", "heart", "lobster"]

9. Replace Multiple Array Elements

var redThings = ["strawberry", "apple", "ruby", "lipstick", "heart", "lobster"]
redThings[1...2] = ["blood", "cherry"]
print (redThings)
//["strawberry", "blood", "cherry", "lipstick", "heart", "lobster"]

8. Iterate Through a Bunch of Numbers

for i in 1...5 {
  print (i)


//If you want to print them all out on the same line
for i in 1...5 {
    print(i, terminator: "")

7. Use Half-Open Ranges to Aid Array Iteration

Half-open ranges don’t include the final value. This can prevent the annoying array.count – 1 that accounts for indexes starting from a value of 0.

let myRange = [Int](1..<5)
//[1, 2, 3, 4]

let hotThings = ["sun", "fire", "desert", "stove", "soup"]
for i in 0..<hotThings.count {
  print (hotThings[i])

6. Value Check Your Ranges

Simply printing out a range doesn’t produce the result you might be expecting.

let myRange = 1...5
print (1...5)
//Prints 1...5
//Doesn't print [1, 2, 3, 4, 5]
//You need to create an array with this range to do this

But you can value check with a simple range.

let range = 1...5

print (range.contains(2))

print (range.contains(6))

You can even do this with one-sided ranges.

let range = ...5

print (range.contains(2))
print (range.contains(-500))
print (range.contains(6))

There is also a special pattern matching operator to indicate whether a value is included in a range. It has the same function as contains.

let specialNumber = 9
print(0...10 ~= specialNumber) //true

5. Make Intervals

While not as simple as using just “…”, you can create intervals over a range by using stride.

let interval = 10
for n in stride(from: 0, to: 50, by: interval) {
    print (n)


//If you want it to print 50 as well, change "to" to "through"

for n in stride(from: 0, through: 50, by: interval) {
    print (n)   

//Also includes 50

4. Make Elegant Switch Statements

let testScore = 70
var comment = String()

switch testScore {
case 0..<60: comment = "What happened?"
case 60..<75: comment = "Needs work"
case 75..<85: comment = "Not bad"
case 85...100: comment = "You Rock"
default: break

print (comment)
//Needs work

3. Create Empty Ranges

Maybe you have 0 numbers in a range and want to check if it is empty.

//This range might look empty, but it includes itself, a range from 5 to 5.

let tinyRange = 5...5
print(tinyRange.contains(5)) //true
print (tinyRange.isEmpty) //false

//This is empty because there are no numbers between 2 and less than 2.
let emptyRange = 2..<2
print (emptyRange.contains(2)) //false
print (emptyRange.isEmpty) //true

2. Count Range Items and Get Their Bounds

let largeRange = 1...5000
print (largeRange.count) //5000
print (largeRange.lowerBound) //1
print (largeRange.upperBound) //5000

Creating a range is the same as creating an array of numbers. So a lot of what you can do with arrays can be done with ranges. For example, finding the minimum and maximum values.

let largeRange = 1...5000
print (largeRange.min()) //Optional(1)
print (largeRange.max()) //Optional(5000)

1. Clamp Ranges Together

You can’t just add ranges together.

let range = 0...10
let range2 = 11...20
let combinedRange = range + range2


But you can clamp one to another, which further restricts a range.

let range1 = 0...20
let range2 = 10...100
let clampedRange = range1.clamped(to: range2)

print (clampedRange.contains(21)) //false

Clamping takes the overlapping values. You have 0-20 and 10-100. What overlaps is 10-20. If the ranges don’t overlap, the result is a range with just the first number of what is being clamped to.

let range1 = 0...10
let range2 = 20...100
let clampedRange = range1.clamped(to: range2)

print (clampedRange.contains(21)) //false

Also, the range types (regular, open or closed) must be the same in order to clamp.

let range1 = 0..<20
let range2 = 10...100
let clampedRange = range1.clamped(to: range2)

//Error. This does not create a range of 10...<20

Leave a Comment

Your email address will not be published. Required fields are marked *