O'Reilly logo

Mastering Swift 4 - Fourth Edition by Jon Hoffman

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Filtering with the where statement

In this example, we will take an array of integers and print out only the even numbers. However, before we look at how to filter the results with the where statement, let's look at how to do this without the where statement:

for number in 1...30 {  
  if number % 2 == 0 { 
    print(number) 
  } 
} 

In this example, we use a for-in loop to cycle through the numbers 1 to 30. Within the for-in loop, we use an if conditional statement to filter out the odd numbers. In this simple example, the code is fairly easy to read, but let's see how we can use the where statement to use fewer lines of code and make them easier to read:

for number in 1...30 where number % 2 == 0 {  
  print(number) 
} 

We still have the same for-in loop ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required