Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can Swift switch statements have another switch in a case?

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?

like image 495
Maury Markowitz Avatar asked Feb 17 '16 21:02

Maury Markowitz


People also ask

Can switch case have multiple conditions Swift?

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.

Can you have a switch statement within a switch statement?

Nested-Switch statements refers to Switch statements inside of another Switch Statements.

Can switch case have multiple conditions?

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.

How many cases switch statement can have?

A switch statement may only have one default clause; multiple default clauses will result in a SyntaxError .


2 Answers

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")
  }
}
like image 184
vadian Avatar answered Sep 22 '22 09:09

vadian


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")

}
like image 26
tktsubota Avatar answered Sep 20 '22 09:09

tktsubota