Junior — Middle
Can you explain the purpose and usage of the 'where' construct in Swift?
sobes.tech AI
Answer from AI
In Swift, the where clause is used to add additional conditions in various contexts such as loops, switch statements, generic type declarations, and collection filtering.
For example:
- In a
forloop, you can filter elements:
for number in 1...10 where number % 2 == 0 {
print(number) // Will print only even numbers
}
- In a
switchstatement,whereallows refining the case condition:
let point = (x: 1, y: 1)
switch point {
case let (x, y) where x == y:
print("Point on the diagonal")
default:
print("Other point")
}
- In generics,
wheresets constraints on types:
func findIndex<T: Equatable>(of valueToFind: T, in array: [T]) -> Int? where T: Comparable {
// Function is available only for types that are both Equatable and Comparable
}
Thus, where helps write more expressive and safe code by clarifying conditions and constraints.