... 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
网友评论