 # Switch Statement: where Clause

Hi.
Right now I’m in Switch statements with where Clause.
In this exercise is an example:

ar randomNumber = Int.random(in: 0…10)

switch randomNumber {
case let x where x % 2 == 0:
print("(randomNumber) is even")
case let x where x % 2 == 1:
print("(randomNumber) is odd")
default:
print(“Invalid”)
}

What I don’t understand in this exercise is: why we use as divine symbol % and why there are this == at the end of both cases?

Hi - welcome back to the forums!

Let’s look at one of the `case` statements from your code block, and break it down. We’ll use this line:

`case let x where x % 2 == 0:`

• `case` - we know the `case` keyword defines a possible scenario that our `switch` is designed to handle.

• `let x` - here we are doing what Swift refers to as “value binding”; we are using a temporary variable (`x`) to hold the value we are considering in this case.

• `where x % 2 == 0` - in a case statement, `where` allows you to expand the situations to which the `case` applies. Here we are only interested in values of `x` where we can divide it by 2 and have a 0 remainder. (We are using the remainder `%` operator, which you can read more about here.)

So, our first case - `case let x where x % 2 == 0:` - deals with values of `randomNumber` which are even. We are taking `randomNumber`, putting it temporarily into the variable `x`, and then checking that its remainder (the `%` operator) is equal to 0 by using the equality (“equal to”) operator `==`.

Similarly, in our second case - `case let x where x % 2 == 1:` - we are taking `randomNumber` and putting it temporarily into the variable `x`, then checking to see if its remainder is 1.

Does that help at all? 3 Likes

Oh wow great explanation @thepitycoder!

1 Like