Skip to content

Latest commit

 

History

History
75 lines (59 loc) · 2.16 KB

2.6 - Range Operators.md

File metadata and controls

75 lines (59 loc) · 2.16 KB

Range operators are shortcuts for expressing a range of values. Swift has several.

Closed Range Operator

The closed range operator (a...b) defines a range which runs from a to b, including a and b. a must not be greater than b.

A good use case is for-in loops:

for index in 1...5 {
    print("\(index) times 5 is \(index * 5)")
}
// 1 times 5 is 5
// 2 times 5 is 10
// 3 times 5 is 15
// 4 times 5 is 20
// 5 times 5 is 25

Half-Open Range Operator

The half-open range operator (a..<b) defines a range from a to b, which includes a but not b. These are particularily useful when you want to work with arrays, e.g.:

let names = ["Anna", "Alex", "Brian", "Jack"]
let count = names.count
for i in 0..<count {
    print("Person \(i + 1) is called \(names[i])")
}
// Person 1 is called Anna
// Person 2 is called Alex
// Person 3 is called Brian
// Person 4 is called Jack

One-sided ranges

These are ranges that omit either the first or last value (e.g. ...5). They include all values up til that point. As a result, they can be useful in iterating over arrays:

for name in names[2...] {
    print(name)
}
// Brian
// Jack

for name in names[...2] {
    print(name)
}
// Anna
// Alex
// Brian

They can also be used in the half-open variant

for name in names[..<2] {
    print(name)
}
// Anna
// Alex

and in other contexts. One sided ranges that omit the first value can't be iterated over because there is no explicit start point. One sided ranges that omit the last value can be iterated over, but must include an explicit end condition. You can also see if values are present:

let range = ...5
range.contains(7)   // false
range.contains(4)   // true
range.contains(-1)  // true

Previous Note| Back To Contents | Next Section