Range operator (1...5)
Range operators is a shortcuts for expressing a range of values.
- Closed range
a...b
- Half-open range
a..<b
- Half-open range used on an array
- One-sided-ranges
[a...]
and[...a]
- Further reading
Closed range a...b
for i in 1...4 {
print(i)
}
// 1
// 2
// 3
// 4
Half-open range a..<b
for i in 1..<4 {
print(i)
}
// 1
// 2
// 3
Half-open range used on an array
let players = ["Ayesha", "Beatrix", "Chris", "Daisy"]
for i in 0..<players.count {
print("Player \(i + 1) is \(players[i])")
}
// Player 1 is Ayesha
// Player 2 is Beatrix
// Player 3 is Chris
// Player 4 is Daisy
One-sided-ranges [a...]
and [...a]
let players = ["Ayesha", "Beatrix", "Chris", "Daisy"]
print(players[2...]) // ["Chris", "Daisy"]
print(players[...2]) // ["Ayesha", "Beatrix", "Chris"]
print(players[..<2]) // ["Ayesha", "Beatrix"]