I've looked at all of Apple's documentation, as well as multiple end-user blogs and similar... and not one single example of a switch
statement with multiple lines in the case
, let alone another switch
. I tried a couple of different syntaxes, but no go, it always complains about an unused closure. Is this possible?
Unlike C, Swift allows multiple switch cases to consider the same value or values. In fact, the point (0, 0) could match all four of the cases in this example. However, if multiple matches are possible, the first matching case is always used.
Nested-Switch statements refers to Switch statements inside of another Switch Statements.
The switch can includes multiple cases where each case represents a particular value. Code under particular case will be executed when case value is equal to the return value of switch expression. If none of the cases match with switch expression value then the default case will be executed.
A switch statement may only have one default clause; multiple default clauses will result in a SyntaxError .
Of course it's possible
enum Alphabet {
case Alpha, Beta, Gamma
}
enum Disney {
case Goofy, Donald, Mickey
}
let foo : Alphabet = .Beta
let bar : Disney = .Mickey
switch foo {
case .Alpha, .Gamma: break
case .Beta:
switch bar {
case .Goofy, .Donald: break
case .Mickey: print("Mickey")
}
}
Yes, nested switch statements and multiple lines in the cases are both possible.
let firstNumber = 0
let secondNumber = 3
switch firstNumber {
case 0:
switch secondNumber {
case 0:
print("First and second numbers are 0")
default:
print("First number is 0, second number is not")
}
default:
print("First number is not 0")
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With