Looping Conditionally Through a Collection - Swift 2.0, Xcode 7 and Interface Builder - iOS 9 Swift Programming Cookbook (2015)

iOS 9 Swift Programming Cookbook (2015)

Chapter 1. Swift 2.0, Xcode 7 and Interface Builder

1.14 Looping Conditionally Through a Collection

Problem

You want to go through the objects inside a collection conditionally and state your conditions right inside the loop’s statement.

Solution

Use the new for x in y where syntax, specifying a where clause right in your for loop. For instance, here I will go through all the keys and values inside a dictionary and only get the values that are integers:

let dic = [

"name" : "Foo",

"lastName" : "Bar",

"age" : 30,

"sex" : 1,

]

for (k, v) in dic where v is Int{

print("The key \(k) contains an integer value of \(v)")

}

Discussion

Prior to Swift 2.0, you’d have to create your conditions before you got to the loop statement--or even worse, if that wasn’t possible and your conditions depended on the items inside the array, you’d have to write the conditions inside the loop. Well, no more.

Here is another example. Let’s say that you want to find all the numbers that are divisible by 8, inside the range of 0 to 1000 inclusively:

let nums = 0..<1000

let divisibleBy8 = {$0 % 8 == 0}

for n in nums where divisibleBy8(n){

print("\(n) is divisible by 8")

}

And of course you can have multiple conditions for a single loop:

let dic = [

"name" : "Foo",

"lastName" : "Bar",

"age" : 30,

"sex" : 1,

]

for (k, v) in dic where v is Int && v as! Int > 10{

print("The key \(k) contains the value of \(v) that is larger than 10")

}

See Also