Maury Markowitz
Maury Markowitz

Reputation: 9293

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?

Upvotes: 8

Views: 8391

Answers (2)

tktsubota
tktsubota

Reputation: 9401

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

}

Upvotes: 2

vadian
vadian

Reputation: 285230

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

Upvotes: 15

Related Questions