Swift 区间运算符 笔记
2017-09-13 本文已影响39人
json_jie
... or ..<
// 闭区间
for index in 1 ... 5 {
print("闭区间 is index = \(index)")
}
print("=================")
/*
闭区间 is index = 1
闭区间 is index = 2
闭区间 is index = 3
闭区间 is index = 4
闭区间 is index = 5
*/
//半闭区间
for index in 1 ..< 5 {
print("半闭区间 is index = \(index)")
}
print("=================")
/*
半闭区间 is index = 1
半闭区间 is index = 2
半闭区间 is index = 3
半闭区间 is index = 4
*/
//单侧区间
//闭区间有另外一种形式来让区间朝一个方向尽可能的远——比如过,一个包含数组所有元素的区间,从索引 2 到数组的结束。在这种情况下,你可以省略区间运算符一侧的值。因为运算符只有一侧有值,所以这种区间叫做单侧区间
let names = ["Anna", "Alex", "Brian", "Jack"]
for name in names[2...] {
print(name)
}
/*
Brian
Jack
*/
print("=================")
for name in names[...2] {
print(name)
}
/*
Anna
Alex
Brian
*/
print("=================")
for name in names[..<2] {
print(name)
}
/*
Anna
Alex
*/
print("=================")
let range = ...5
range.contains(7) // false
range.contains(4) // true
range.contains(-1) // true