Swift: Switch case with multiple patterns cannot bind to variable

后端 未结 1 599
日久生厌
日久生厌 2020-12-17 04:39

In the official Swift Programming Language guide, it has this to say about switch case: \"...if the case contains multiple patterns that match the control expression, none o

相关标签:
1条回答
  • 2020-12-17 05:32

    It means that case labels with multiple patterns cannot declare variables.

    This is allowed:

    let somePoint = (1, 1)
    switch somePoint {
    // Case with multiple patterns without binding
    case (0, _),
         (_, 0):
        println("(\(somePoint.0), \(somePoint.1)) is on an axis")
    default:
        println("(\(somePoint.0), \(somePoint.1)) is not of an axis")
    }
    

    This is allowed, too:

    let somePoint = (1, 1)
    switch somePoint {
    // Case with single patterns with binding
    case (0, let y):
        println("(0, \(y)) is on an axis")
    case (let x, 0):
        println("(\(x), 0) is on an axis")
    default:
        println("(\(somePoint.0), \(somePoint.1)) is not of an axis")
    }
    

    However, this is prohibited:

    let somePoint = (1, 1)
    switch somePoint {
    // Case with multiple patterns that have bindings
    case (0, let y),
         (let x, 0):
        println("(\(x), \(y)) is on an axis")
    default:
        println("(\(somePoint.0), \(somePoint.1)) is not of an axis")
    }
    

    The above produces an error:

    error: 'case' labels with multiple patterns cannot declare variables
    
    0 讨论(0)
提交回复
热议问题