What are one-sided ranges in Swift?

We can use one-sided ranges to create a range without upper or lower bound values.

Syntax

a...

This will include everything from the lower bound a.


...a

This will include everything before the upper bound a. a is included in the range.


..<a

This will include everything before the upper bound a. a is excluded in the range.


Example for one-sided range a...

let numbers = 1...
print(numbers);
print(numbers.contains(1))
print(numbers.contains(1000000000))

In the code above, we created a one-sided range 1.... This range will contain every value from 1.

Example for one-sided range ...a

let numbers = ...10
print(numbers);
print(numbers.contains(-1))
print(numbers.contains(10))
print(numbers.contains(-1000000000))

In the code above, we created a one-sided range ...10. This range will contain every value before 10 (10 is included in the range).

Example for one-sided range ..<a

let numbers = ..<1
print(numbers);
print(numbers.contains(-1000000000))
print(numbers.contains(1)) // false

In the code above, we created a one-sided range ..<1. This range will contain every value before 1 (1 is excluded from the range). After that, we checked if 1 is present in the range. This will return false.


One-sided range in a real example

let fruits = ["apple", "grapes", "banana", "water melon", "guava"]
print(fruits[1...]) // Print all items from index 1
print(fruits[...2]) // Prints all items upto 2nd index, 2nd index element also included
print(fruits[..<2]) // Prints all items upto 2nd index, 2nd index element is not inclulded

In the code above, we used the following to slice the array.

  • fruits[1...]: This will return all the array values from index 1.

  • fruits[...2]: This will return all the array values before index 2; the value at index 2 is also included.

  • fruits[..<2]: This will return all the array values before index 2; the value at index 2 is not included.

Free Resources