带过滤的 For-in 循环

  1. where 条款

通过添加 where 子句,你可以将迭代限制为满足给定条件的迭代。

for i in 0..<5 where i % 2 == 0 {
    print(i)
}

// 0
// 2
// 4

let names = ["James", "Emily", "Miles"]

for name in names where name.characters.contains("s") {
    print(name)
}

// James
// Miles
  1. case 条款

当你只需要迭代匹配某些模式的值时,它很有用:

let points = [(5, 0), (31, 0), (5, 31)]
for case (_, 0) in points {
    print("point on x-axis")
}

//point on x-axis
//point on x-axis

你也可以通过在绑定常量后添加 ? 标记来过滤可选值并在适当时解包它们:

let optionalNumbers = [31, 5, nil]
for case let number? in optionalNumbers {
    print(number)
}

//31    
//5