swift case falling through

前端 未结 5 871
时光说笑
时光说笑 2020-12-07 21:30

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         


        
相关标签:
5条回答
  • 2020-12-07 22:01
    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")
    }
    
    0 讨论(0)
  • 2020-12-07 22:02

    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
    }
    
    0 讨论(0)
  • 2020-12-07 22:10

    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.

    0 讨论(0)
  • 2020-12-07 22:11

    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.

    0 讨论(0)
  • 2020-12-07 22:15
    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.

    0 讨论(0)
提交回复
热议问题