Blog / August 22, 2022 / 2 mins read / By Mahi Garg

For loop with where clause: Swift

For loop is an inevitable part of any programming language. It iterates over every element of the collection type data including array, set, and dictionary, and does the operation as per the code.

Let us see an example of the same. Consider an array of integers and a for loop accessing its even integers.

//array example
let numbers = [23,62,6,12,87,55,45,22]
//for loop
for number in numbers {
    print(number)
}

Above swift code will print all integers in the array. But sometimes we need only elements on certain conditions like even number, or positive number. This can be achieved by giving a where clause with the for loop body.

Let us see the code for filtering even numbers.

//for loop with where
for number in numbers where number % 2 == 0 {
    print(number)
}
// print 62 6 12 22

Here data is filtered according to where clause i.e., only even numbers will be printed. Similarly, we can filter data on more than one condition using (||) or and (&&) depending on the use case.

Let us look at this with an example.

//for loop with where 
for number in numbers where number % 2 == 0 || number > 50 {
    print(number)
}
// 62 6 12 87 55 22

Here data is filtered according to where clause i.e., even numbers or numbers greater than 50 will be printed.

Now let us consider case printing numbers that are even and greater than 50.

//for loop with where
for number in numbers where number % 2 == 0 && number > 50 {
print(number)
}
// prints even numbers and number greater than 50 
// 62 

Here data is filtered according to where clause i.e. even numbers and numbers greater than 50 will be printed.

Comments