Swift Switch Statement
Learn how to use the Swift switch statement as a cleaner alternative to complicated "if.. else if... "statements. Even if you have used switch statements in other languages, you should be aware of some differences in the Swift implementation.
In the previous lesson, we looked at how to control program execution flow using the if
and else
statements. While these statement constructs work well for testing a limited number of conditions, they quickly become unwieldy when dealing with larger numbers of possible conditions. To simplify such situations, Swift has inherited the switch
statement from the C programming language.
In this lesson, we will explore the Swift implementation of the switch
statement in detail.
Note: Those familiar with the
switch
statement from other programming languages should be aware that the Swiftswitch
statement has some key differences from other implementations.
Why use a switch
statement?
For a small number of logical evaluations of a value, the if ... else if ...
construct is perfectly adequate. Unfortunately, any more than two or three possible scenarios can quickly make such a construct both time-consuming to write and difficult to read. For such situations, the switch
...