where
clauseBy 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
case
clauseIt'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