Clicky

iOS Dev Nugget 292 for-where

.

Need to run a code review on your codebase? Hire me

We often need to go through elements in a collection, but only operating on elements that fulfill a certain condition. E.g. only if the number is odd:

for i in 1...10 {
    if i % 2 == 0 {
        print(i)
    }
}

Here's another way to do it, using filter():

for i in (1...10).filter({$0 % 2 == 0}) {
    print(i)
}

But this is probably the more idiomatic way to do it in Swift:

for i in 1...10 where i % 2 == 0 {
    print(i)
}

Note that you can use where clauses in a similar manner in other places, such as in switch-case statements.

Your feedback is valuable: Do you want more nuggets like this?   Yes   or   No

.

.

Like this and want such iOS dev nuggets to be emailed to you, weekly?

Sign Me Up! or follow @iosdevnuggets on Twitter

.

View archives of past issues