swift case falling through

Switch StatementSwift

Switch Statement Problem Overview


Does swift have fall through statement? e.g if I do the following

var testVar = "hello"
var result = 0

switch(testVal)
{
case "one":
    result = 1
case "two":
    result = 1
default:
    result = 3
}

is it possible to have the same code executed for case "one" and case "two"?

Switch Statement Solutions


Solution 1 - Switch Statement

Yes. You can do so as follows:

var testVal = "hello"
var result = 0

switch testVal {
case "one", "two":
    result = 1
default:
    result = 3
}

Alternatively, you can use the fallthrough keyword:

var testVal = "hello"
var result = 0

switch testVal {
case "one":
    fallthrough
case "two":
    result = 1
default:
    result = 3
}

Solution 2 - Switch Statement

var testVar = "hello"

switch(testVar) {
    
case "hello":

    println("hello match number 1")

    fallthrough

case "two":

    println("two in not hello however the above fallthrough automatically always picks the     case following whether there is a match or not! To me this is wrong")

default:

    println("Default")
}

Solution 3 - Switch Statement

case "one", "two":
    result = 1

There are no break statements, but cases are a lot more flexible.

Addendum: As Analog File points out, there actually are break statements in Swift. They're still available for use in loops, though unnecessary in switch statements, unless you need to fill an otherwise empty case, as empty cases are not allowed. For example: default: break.

Solution 4 - Switch Statement

Here is example for you easy to understand:

let value = 0

switch value
{
case 0:
    print(0) // print 0
    fallthrough
case 1:
    print(1) // print 1
case 2:
    print(2) // Doesn't print
default:
    print("default")
}

Conclusion: Use fallthrough to execute next case (only one) when the previous one that have fallthrough is match or not.

Solution 5 - Switch Statement

The keyword fallthrough at the end of a case causes the fall-through behavior you're looking for, and multiple values can be checked in a single case.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionBilal Syed HussainView Question on Stackoverflow
Solution 1 - Switch StatementCezary WojcikView Answer on Stackoverflow
Solution 2 - Switch StatementGlenn TismanView Answer on Stackoverflow
Solution 3 - Switch StatementnhgrifView Answer on Stackoverflow
Solution 4 - Switch StatementKhuongView Answer on Stackoverflow
Solution 5 - Switch StatementRussell BorogoveView Answer on Stackoverflow