Range Operators
Range Operators
Introduction - Closed Range Operator
Hello,
In this lesson, we will learn about the range operators provided to us by Swift.
The first thing we will learn is the Closed Range Operator. This operator creates a closed range, including numbers defined by it.
Let's take a look at our example.
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 25The Half-Open Range
The Half-Open Range operator creates a half-open range, as we can understand from its name.
When we look at the example below carefully, although the length of the array is 4, the range is between 0 and 3.
let cats = ["Lucy", "Garfield", "Tom", "Sylvester"]
let count = cats.count
for i in 0..<count {
print("Cat \(i + 1) is called \(cats[i])")
}
// Person 1 is called Anna
// Person 2 is called Alex
// Person 3 is called Brian
// Person 4 is called Jack