closed range operator (a...b)는 a와 b를 포함한 a와 b사이의 범위를 나타낸다. 당연하다면 당연한거겠지만 a는 b보다 커서는 안된다.
for-in 루프와 같이 일정한 범위내에서의 순환이 필요할 때 사용하면 좋다.
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 (a..<b)는 a와 b의 사잇값들과 a를 포함한 범위를 말한다. half open이라 하는 이유는 a는 포함하지만 b는 포함하지 않기 때문이다.
half-open range operator은 Array처럼 0가 첫번째 요소를 의미하는 자료구조에서 사용하기 편하다.
let names = ["Anna", "Alex", "Brian", "Jack"]
let count = names.count // count에 4가 할당된다.
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