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 as in the previous example. However, we have now put the where statement at the end; therefore, we only loop through the even numbers. Using the where statement shortens our example by two lines and makes it easier to read because the where clause is on the same line as the for-in loop, rather than being embedded in the loop itself.

Now let's look at how we could filter with the for-case statement.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset