Switch statement in Swift

后端 未结 7 1604
礼貌的吻别
礼貌的吻别 2020-12-01 01:26

I\'m learning syntax of Swift and wonder, why the following code isn\'t working as I expect it to:

for i in 1...100{

    switch (i){
    case 1:
        Int         


        
7条回答
  •  -上瘾入骨i
    2020-12-01 01:50

    Switch statements in Swift support value bindings.
    This allows you to assign a value that matches a certain condition (evaluated via the where clause) to a temporary variable (x & y here):

    for i in 1...100 {
        switch (i){
        case let x where x%3 == 0:
            println("Fizz")
        case let y where y%5 == 0:
            println("Buzz")
        default:
            println("\(i)")
        }
    }
    

    You could also use the assigned temp value in the case body.

    Update:
    Matt Gibson points out in the comments, that you can omit the assignment to a temp var if you are not going to use it in the case body.
    So a more concise version of the above code would be:

    for i in 1...100 {
        switch (i){
        case _ where i%3 == 0:
            println("Fizz")
        case _ where i%5 == 0:
            println("Buzz")
        default:
            println("\(i)")
        }
    }
    

    Side note: Your 2 code samples are slightly different (the first one uses the range 0-100 as input, while the second one operates on 1-100). My sample is based on your first code snippet.

提交回复
热议问题