Where clause

     In Swift, the where clause is used as part of a for loop, a switch statement, or a catch block to add additional conditions that must be true for the loop, switch, or catch block to execute.

Here are some examples of how the where clause can be used in Swift: 

  • Using where with a for loop

let numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

for number in numbers where number % 2 == 0 {
    print("\(number) is even")
}

In this example, the where clause is used to filter the elements of the numbers array so that only even numbers are printed. The where clause is added after the in keyword and specifies a condition that must be true for the loop body to execute. In this case, the condition is that the number must be even (i.e., the remainder when it is divided by 2 must be 0).


  • Using where with a switch statement

let value = 42

switch value {
case let x where x < 0:
    print("Negative")
case let x where x > 0 && x < 10:
    print("Single digit positive")
case let x where x >= 10:
    print("Double digit or higher positive")
default:
    print("Zero")
}

In this example, the where clause is used to add additional conditions to the case statements of the switch statement. Each case statement has a pattern that matches a range of values, and a where clause that specifies additional conditions that must be true for that case to execute. The default case is executed if none of the other cases match.


  • Using where with a catch block

do {
    // code that might throw an error
} catch let error as NSError where error.code == 404 {
    print("File not found")
} catch {
    print("Unknown error: \(error.localizedDescription)")
}

In this example, the where clause is used to filter the errors that are caught by the catch block. The first catch block catches only errors that are of type NSError and have an error code of 404 (i.e., "File not found"). The second catch block catches all other errors and prints a generic error message.

    Overall, the where clause is a powerful tool in Swift that allows you to add additional conditions to loops, switches, and catch blocks. By using the where clause, you can write code that is more concise and expressive, while still maintaining the flexibility and readability of Swift.





Comments

Popular Posts