模式匹配并在单个Switch语句中有条件地绑定

Ale*_*ica 3 switch-statement conditional-binding swift swift2 swift3

有没有办法把这个if/ else if/ elseladder写成switch语句?

let x: Any = "123"

if let s = x as? String {
    useString(s)
}
else if let i = x as? Int {
    useInt(i)
}
else if let b = x as? Bool {
    useBool(b)
}
else {
    fatalError()
}
Run Code Online (Sandbox Code Playgroud)

这是我的尝试:

switch x {
case let s where s is String:   useString(s)
case let i where i is Int:      useInt(i)
case let b where b is Bool:     useBool(b)
default: fatalError()
}
Run Code Online (Sandbox Code Playgroud)

它成功地选择了正确的道路,但s/ i/ b是类型还是Any.该is检查没有铸造他们的任何影响.这迫使我as!在使用前强制施放.

有没有办法在一个switch语句中打开类型并将其绑定到名称?

Ham*_*ish 9

当然,您可以使用条件转换模式 case let x as Type:

let x: Any = "123"

switch x {
case let s as String:
    print(s)   //use s
case let i as Int:
    print(i)   //use i
case let b as Bool:
    print(b)   //use b
default:
    fatalError()
}
Run Code Online (Sandbox Code Playgroud)