Using case and where statements with conditional statements and loops
As we saw with switch
statements, the case
and where
statements within a switch
statement can be very powerful. Using case
and where
statements within our conditional statements can also make our code much smaller and easier to read. Conditional statements and loops, such as if
, for
, and while
, can also make use of the where
and case
keywords. Let's take a look at some examples, starting off with using the where
statement to filter the results in a for-in
loop.
Filtering with the where statement
In this example, we take an array of integers and print out only multiples of 3. However, before we look at how to filter the results with the where
statement, let's take a look at how to do this without the where
statement:
for number in 1...30 {
if number % 3 == 0 {
print(number)
}
}
In this example, we use a for-in
loop to cycle through the numbers 1 to 30. Within the for-in...