0
0
Swiftprogramming~5 mins

For-in with where clause in Swift

Choose your learning style9 modes available
Introduction
A for-in loop with a where clause helps you look at only the items you want from a list, making your work easier and faster.
When you want to find only the students who scored above 80 in a test.
When you need to list all products that are currently in stock.
When you want to print only the names of employees who work in a specific department.
When you want to process only the even numbers from a list of numbers.
Syntax
Swift
for item in collection where condition {
    // code to run for each item that meets the condition
}
The 'where' clause filters items before the loop runs its code.
Only items that meet the condition inside 'where' will be used inside the loop.
Examples
This prints only even numbers from the 'numbers' list.
Swift
for number in numbers where number % 2 == 0 {
    print(number)
}
This prints the names of students who scored more than 80.
Swift
for student in students where student.grade > 80 {
    print(student.name)
}
This prints the names of products that are in stock.
Swift
for product in products where product.inStock {
    print(product.name)
}
Sample Program
This program prints only the even numbers from the list.
Swift
let numbers = [1, 2, 3, 4, 5, 6]
for number in numbers where number % 2 == 0 {
    print(number)
}
OutputSuccess
Important Notes
The where clause makes your loop cleaner by avoiding extra if statements inside the loop.
You can use any condition that returns true or false in the where clause.
If no items meet the condition, the loop body will not run at all.
Summary
Use 'for-in with where' to loop only over items you want.
It helps keep your code simple and easy to read.
The condition in 'where' decides which items the loop uses.