带铸造外壳的开关

God*_*her 5 ios swift

我想用一个开关来做到这一点:

 protocol TestProtocol {}

 class A: TestProtocol {}
 class B: TestProtocol {}

 var randomObject: TestProtocol

 if let classAObj = randomObject as? A {
 } else if let classBObj = randomObject as? B {}
Run Code Online (Sandbox Code Playgroud)

我想要这样的东西:

switch randomObject {
    case let classAObj = randomObject as? A:
         ...
    case let classBObj = randomObject as? B:
         ....
     default:
         fatalError("not implemented")
}
Run Code Online (Sandbox Code Playgroud)

Mar*_*n R 10

你当然可以:

switch randomObject {
case let classAObj as A:
    // Here `classAObj` has type `A`.
    // ...
case let classBObj as B:
    // Here `classBObj` has type `B`.
    // ...
default:
    fatalError("not implemented")
}
Run Code Online (Sandbox Code Playgroud)

在模式匹配表达式中,它是as、不是as?、并且= randomObject不需要,要匹配的值在switch关键字之后立即给出。

而只是为了完整起见:模式匹配 case let 可以也可以使用if语句(或在/换语句):

if case let classAObj as A = randomObject {

} else if case let classBObj as B = randomObject {

}
Run Code Online (Sandbox Code Playgroud)

但是,在这种情况下,没有理由这样做。

  • @koropok:我怀疑这有什么不同。通常你想要向下转换的对象,那么无论如何你都需要 `as`。 (2认同)