Learn Swift's range operators
Swift provides two new types of range operators that you’ll want to remember: the closed range operator (...
) and the half-open range operator (..<
):
The closed range operator is represented by three consecutive periods (...
). Use this operator to specify a range that includes both its first and second endpoints. For example, consider this idiomatic loop in C:
for (int i = 1; i <= 10; i++) {
printf("%d + %d is %d\n", i, i, i+i);
}
In Swift, this would be:
for i in 1...10 {
print("\(i) + \(i) is \(i+i)")
}
// 1 + 1 is 2
// 2 + 2 is 4
// 3 + 3 is 6
// 4 + 4 is 8
// 5 + 5 is 10
// 6 + 6 is 12
// 7 + 7 is 14
// 8 + 8 is 16
// 9 + 9 is 18
// 10 + 10 is 20
You could also express this mathematically as the closed interval of integers that are greater than or equal to 1 and less than or equal to 10:
[1,10] = { x | 1 ≤ x ≤ 10 }
The half-open range operator is represented by two consecutive periods followed by a less-than symbol (..<
). Use this operator to specify a range that includes its first endpoint but not its second, as is common when iterating over arrays and other containers with zero-based indices. For example, consider this idiomatic loop in C:
const int count = 10;
char* stars[count] = {
"Alnilam", "Alnitak", "Bellatrix", "Betelgeuse", "Canopus",
"Mintaka", "Polaris", "Rigel", "Saiph", "Sirius"
};
for (int i = 0; i < count; i++) {
printf("%s\n", stars[i]);
}
In Swift, this would be:
var stars = ["Alnilam", "Alnitak", "Bellatrix", "Betelgeuse", "Canopus",
"Mintaka", "Polaris", "Rigel", "Saiph", "Sirius"]
for index in 0..<stars.count {
print(stars[index])
}
// Alnilam
// Alnitak
// Bellatrix
// Betelgeuse
// Canopus
// Mintaka
// Polaris
// Rigel
// Saiph
// Sirius
You could also express this mathematically as the left-closed, right-open interval of integers that are greater than or equal to 1 and less than 10:
[1,10) = { x | 1 ≤ x < 10 }
It’s important to note that both range operators expect the first endpoint to be less than the second endpoint. If you’d like to iterate over a range of numbers in reverse, use the reverse
function:
print("Begin countdown:")
for i in reverse(1...10) {
print(i)
}
// Begin countdown:
// 10
// 9
// 8
// 7
// 6
// 5
// 4
// 3
// 2
// 1