0
0
Swiftprogramming~5 mins

For-in with where clause in Swift - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What does the where clause do in a for-in loop in Swift?
It filters the items in the loop, so the loop only runs for elements that meet the condition specified in the where clause.
Click to reveal answer
beginner
How would you write a for-in loop that prints only even numbers from an array numbers?
Use a where clause to check if the number is even: <br>
for number in numbers where number % 2 == 0 {<br>  print(number)<br>}
Click to reveal answer
intermediate
Can you use multiple conditions in a where clause in Swift's for-in loop?
Yes, you can combine conditions using logical operators like && (and) or || (or) inside the where clause.
Click to reveal answer
beginner
What happens if no elements satisfy the where condition in a for-in loop?
The loop body does not run at all because no elements meet the condition to be processed.
Click to reveal answer
beginner
Why is using a where clause in a for-in loop helpful?
It makes the code cleaner and easier to read by filtering elements directly in the loop instead of using an if statement inside the loop.
Click to reveal answer
What does the where clause do in a Swift for-in loop?
ADeclares a new variable
BFilters elements to loop only over those that meet a condition
CEnds the loop early
DChanges the loop variable type
Which of these is a valid use of where in a for-in loop?
Afor item in items where item.isActive { print(item) }
Bfor item where item.isActive in items { print(item) }
Cwhere item.isActive for item in items { print(item) }
Dfor item in items if item.isActive { print(item) }
Can you use multiple conditions in a where clause?
AYes, using logical operators like && and ||
BNo, only one condition is allowed
CYes, but only with commas
DNo, you must use nested loops
What happens if no elements satisfy the where condition?
AThe loop runs for all elements anyway
BThe loop runs once with a nil value
CThe loop throws an error
DThe loop body does not run
Why might you prefer using a where clause over an if statement inside the loop?
AIt runs faster always
BIt allows modifying the loop variable
CIt makes the code cleaner and easier to read
DIt automatically sorts the elements
Explain how the where clause works in a Swift for-in loop and why it is useful.
Think about how you pick only certain items from a list to work with.
You got /3 concepts.
    Write a Swift for-in loop using a where clause to print only odd numbers from an array.
    Use modulo operator to check odd numbers.
    You got /3 concepts.