Swift 范围运算符
Swift 4支持几种类型的范围操作符,用于简洁地表示一系列数值。
- 闭区间操作符
- 半开区间操作符
- 单侧区间
闭区间操作符
闭合范围运算符(a…b)指定了从a到b的范围(包括a和b,且a的值不应大于b的值)。闭合范围运算符在需要迭代一个范围,并且希望使用所有值(例如在for-in循环中)时非常有用。
示例
for index in 1...10 {
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
6 times 5 is 30
7 times 5 is 35
8 times 5 is 40
9 times 5 is 45
10 times 5 is 50
半开区间操作符
半开放范围运算符(a..<b)指定了从a到b的范围,但不包括b。它被称为半开放范围运算符,因为它包含第一个值,但不包含最后一个值。与闭合范围运算符类似,半开放范围运算符中a的值也不能大于b的值。如果a的值等于b,则结果范围将为空。
半开放范围运算符通常与数组一起使用,用于计算列表的长度。
示例
let names = ["Albert", "Aryan", "Ajeet", "Jill"]
let count = names.count
for i in 0..<count {
print("Person \(i + 1) name is \(names[i])")
}
输出:
Person 1 name is Albert
Person 2 name is Aryan
Person 3 name is Ajeet
Person 4 name is Jill
单侧区间
单侧范围运算符是闭合范围运算符或半开放范围运算符在单个方向上的替代形式。
示例1
let names = ["Albert", "Aryan", "Ajeet", "Jill"]
let count = names.count
for name in names[2...] {
print(name)
}
输出:
Ajeet
Jill
示例2
let names = ["Albert", "Aryan", "Ajeet", "Jill"]
let count = names.count
for name in names[...2] {
print(name)
}
输出:
Albert
Aryan
Ajeet
示例3
let names = ["Albert", "Aryan", "Ajeet", "Jill"]
let count = names.count
for name in names[..<2] {
print(name)
}
输出:
Albert
Aryan