The switch statement where clause in swift is another useful feature for the cases of a switch
statement.
For a given expression, the where
clause allows for additional pattern matching. It can also be used with conditionals such as if
statements and loops.
Let’s pretend we’re writing a program to determine whether a random integer between 0 and 10 is even or odd. The following program can be written:
var number = Int.random(in: 0...10);
switch number {
case let a where a % 2 == 0:
print("\(number) is even");
case let a where a % 2 == 1:
print("\(number) is odd");
default:
print("Invalid");
}
Let’s look at what’s going on in the first line:
var number = Int.random(in: 0...10);
random()
to generate a random integer, Int
, from a range of numbers. Take note of how we’ve used the closed range operator,...
, to represent a numerical range.number
. A standard switch
statement checks the value of number
after the variable declaration:
switch number {
case let a where a % 2 == 0:
print("\(number) is Even");
case let a where a % 2 == 1:
print("\(number) is Odd");
default:
print("Invalid");
}
// Prints: 5 is Odd
where
clause and a condition in each case
. The code for that case
will run if a condition is true
.a
after the let
keyword creates a temporary binding to the number
value. This means that the value of a
becomes the value of number
for the time being. If number
equals 5, then a
equals 5!a
will not be reassigned at any point during the switch
statement, its value will always be constant, the let
keyword is used instead of var
. If you use var
, Swift will issue a compiler warning, advising you to use let
instead:Numbers.swift:6:12: warning: variable 'a' was never mutated; consider changing to 'let' constant
Note: A compiler warning isn’t the same as an error. Even if there is a warning, your program should still run.
where
condition determines whether a
is divisible by two with or without a remainder, as well as whether the number
is even or odd.Because the number generated each time is random, your output is likely to differ from ours if you run this code.
Here are some useful tools to help you along your journey!
Setting up an IDE (Integrated Development Environment) can be difficult for beginners. The Online Compiler will enable you to run your code inside your browser without the need to install an IDE. If you need a more detailed explanation of a specific topic, the best place to find answers is in the Official Documentation.