In Swift, a switch statement allows you to compare a value against multiple possible matching patterns and execute different code blocks based on the matched pattern. Here's an example of how to use a switch statement in Swift:
main.swift227 chars12 lines
In the above example, we first declare a constant number
with a value of 5
. We then use a switch
statement on this value, checking against various cases. The first case checks for a value of 0
, and prints "Number is zero" if it matches. The second case uses a range operator ...
to match any value between 1
and 5
inclusive, and prints "Number is between 1 and 5 inclusive" if it matches. The third case again uses the range operator, but this time with ..<
which matches any value between 6
and 9
, and prints "Number is between 6 and 9" if it matches. Finally, the default
case is executed if none of the previous cases match, and prints "Number is out of range".
Note that in Swift, unlike in other programming languages, switch
statements do not "fall through" to the next case. Once a case
matches, the corresponding code block is executed and the switch
statement is exited. You can use the fallthrough
keyword to achieve fall-through behavior if needed.
gistlibby LogSnag