153

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

Bilal Syed Hussain
  • 8,664
  • 11
  • 38
  • 44

5 Answers5

387

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
}
Twitter khuong291
  • 11,328
  • 15
  • 80
  • 116
Cezary Wojcik
  • 21,745
  • 6
  • 36
  • 36
8
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")
}
Tieme
  • 62,602
  • 20
  • 102
  • 156
Glenn Tisman
  • 163
  • 1
  • 6
8

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.

Twitter khuong291
  • 11,328
  • 15
  • 80
  • 116
7
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.

nhgrif
  • 61,578
  • 25
  • 134
  • 173
2

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.

Russell Borogove
  • 18,516
  • 4
  • 43
  • 50