범위 연산자에는 닫힌 범위연산자, 반 받힌 범위연산자, 단방향 범위연산자가 있습니다.
닫힌 범위 연산자
(a...b)의 형태로 범위의 시작과 끝이 있는 연산자입니다.
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
반 받힌 범위연산자
(a..<b)의 형태로 a부터 b보다 작을 때까지의 범위를 가집니다.
a부터 b-1까지 값. 반 닫힌 범위 연산자는 보통 배열을 다룰 때 많이 사용합니다.
let names = ["Anna", "Alex", "Brian", "Jack"]
for i in 0..<names.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
단방향 범위연산자
[a...] [...a]의 형태로 범위의 시작 혹은 끝만 지정해 사용하는 범위 연산자입니다.
지정한 시작 값 혹은 끝 값을 알아서 범위에 포함시켜줍니다.
for name in names[2...] {
print(name)
}
// Brian
// Jack
for name in names[...2] {
print(name)
}
// Anna
// Alex
// Brian
for name in names[..<2] {
print(name)
}
// Anna
// Alex
let range = ...5
range.contains(7) // false
range.contains(4) // true
range.contains(-1) // true
역방향(큰 값에서 작은 값)으로 범위연산자를 사용하고 싶을 때는 reversed() 메서드를 이용하면 됩니다.
for index in (1...5).reversed() {
print("\(index) times 5 is \(index * 5)")
}
// 5 times 5 is 25
// 4 times 5 is 20
// 3 times 5 is 15
// 2 times 5 is 10
// 1 times 5 is 5
범위연산자는 결과물로 Range 구조체를 반환합니다.
범위연산자를 변수로 받아서 아래와 같이 처리를 할 수 있습니다.
let rangeInstance = 0.0 ..< 10.0 // Range<Double> 타입
print(rangeInstance) // 0.0..<10.0
print(rangeInstance.contains(1.5)) // true
print(rangeInstance.lowerBound) // 0.0
print(rangeInstance.upperBound) // 10.0
~= 연산자
~= 연산자로 해당 범위 내에 값이 있는지 체크를 할 수도 있습니다.
if rangeInstance ~= 2.5 {
print("2.5 in \(rangeInstance)")
// 2.5 in 0.0..<10.0
}
~= 연산자는 제네릭 연산자이기 때문에 String도 사용할 수 있습니다.
let rangeOfString = "a"..."z"
if rangeOfString ~= "b" {
print("b in \(rangeOfString)")
// b in a...z
}
Switch문과 범위연산자
Switch문의 case에서 범위연산자를 사용할 수도 있습니다.
// 숫자의 특정 범위를 조건으로 사용할 수 있음
let approximateCount = 62
let countedThings = "moons orbiting Saturn"
let naturalCount: String
switch approximateCount {
case 0:
naturalCount = "no"
case 1..<5:
naturalCount = "a few"
case 5..<12:
naturalCount = "several"
case 12..<100:
naturalCount = "dozens of"
case 100..<1000:
naturalCount = "hundreds of"
default:
naturalCount = "many"
}
print("There are \(naturalCount) \(countedThings).")
// Prints "There are dozens of moons orbiting Saturn."