lucas_turci
lucas_turci

Reputation: 322

Is there a way of checking more than one condition in Swift switch?

In Swift, I need to make a switch like this:

switch char {
    case "+": statement 1; statement 3
    case "-": statement 2; statement 3
 default: statement 3   
}

However, I don't want to copy the statement 3, because it is actually quite long, so I'm looking for an alternative way (if it exists) to somehow make the switch check every case condition, and execute the default too.

Upvotes: 1

Views: 645

Answers (2)

John Difool
John Difool

Reputation: 5722

The only way you can fallthrough a case and skip over the next one to get you to default is to retest the condition:

switch char {
case "+": statement 1; fallthrough
case "-": if char == "-" { statement 2 }; fallthrough
default: statement 3
}

which at the end of the day, let's be honest, looks awesomely frugly. I suggest you replace your long statements by function calls and keep the control flow you gave above.

Upvotes: 2

matt
matt

Reputation: 535716

Repeated code? Good candidate for a local function:

func statement3() {
    // ... lots of stuff here ...
}
switch char {
    case "+": statement 1; statement3()
    case "-": statement 2; statement3()
 default: statement3()   
}

But if you really want to do statement3 in every case, then just take it out of the switch statement altogether:

switch char {
    case "+": statement 1
    case "-": statement 2
 default: break   
}
statement 3

Upvotes: 6

Related Questions