Swift: Switch case with multiple patterns cannot bind to variable

元气小坏坏 提交于 2019-12-29 06:27:09

问题


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 of those patterns can contain constant or variable bindings."

What does it mean by containing multiple patterns?


回答1:


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


来源:https://stackoverflow.com/questions/30545503/swift-switch-case-with-multiple-patterns-cannot-bind-to-variable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!