Swift Language Loops For-in loop with filtering

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Extensions
> Step 2: And Like the video. BONUS: You can also share it!

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


Got any Swift Language Question?