假设我有一个枚举定义如下:
enum Response {
case Result(String, Int)
case Error(String)
}
Run Code Online (Sandbox Code Playgroud)
然后,我得到了这样的回应:
let resp: Response = // ...
Run Code Online (Sandbox Code Playgroud)
假设我想编写一个switch语句,并以与Result和Error案例相同的方式处理,并将同名的变量绑定到String它们包含的变量.我怎样才能做到这一点?从概念上讲,类似于此:
switch resp {
case let .Result(str, _), let .Error(str):
println("Found: \(str)")
}
Run Code Online (Sandbox Code Playgroud)
在哪里str绑定两次,并_发出信号表明我对Inta Result携带的值不感兴趣.
到目前为止,我能找到的最接近的事情是声明一个这样的内联函数,然后调用它:
func processRespString(str: String) {
println("Found \(str)")
}
switch resp {
case let .Result(str, _): processRespString(str)
case let .Error(str): processRespString(str)
}
Run Code Online (Sandbox Code Playgroud)
有没有更好的办法?
已被接受的Swift 演进提案 SE-0043使用Swift 3 修复了此问题。
enum Response {
case result(String, Int)
case error(String)
}
let resp = Response.error("Some text")
switch resp {
case let .result(str, _), let .error(str):
print("Found: \(str)") // prints Found: Some text
}
Run Code Online (Sandbox Code Playgroud)
使用 Swift 2,之前的 Playground 代码会生成错误:case labels with multiple patterns cannot declare variables。但是,对于 Swift 3,它不会生成任何错误并且具有预期的行为。
| 归档时间: |
|
| 查看次数: |
1668 次 |
| 最近记录: |