在Swift语法里where关键字的作用跟SQL的where一样, 即附加条件判断。
1、 在集合遍历时使用where, 条件为真时执行代码块, 为假时不执行代码块。
let array = [0, 1, 2, 3, 4, 5, 6]
//使用switch遍历
array.forEach {
switch $0 {
case let x where x > 3: //where相当于判断条件
print("后半段")
default:
print("默认值")
}
}
//使用for in遍历
for value in array where value > 2 {
print(value) //输出3 4 5 6
}
for (index, value) in array.enumerated() where index > 2 && value > 3 {
print("下标:\(index), 值:\(value)")
}
输出:
默认值
默认值
默认值
默认值
后半段
后半段
后半段
3