Swift Language For-in loop with filtering


Example

  1. where clause

By adding a where clause you can restrict the iterations to ones that satisfy the given condition.

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 clause

It's useful when you need to iterate only through the values that match some pattern:

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

Also you can filter optional values and unwrap them if appropriate by adding ? mark after binding constant:

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

//31    
//5