ios - 带铸件的开关

标签 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 {}

我想要这样的东西:

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

最佳答案

当然可以:

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")
}

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

为了完整起见:模式匹配 case let 也可以用于 if 语句(或 while/for 语句):

if case let classAObj as A = randomObject {

} else if case let classBObj as B = randomObject {

}

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

关于ios - 带铸件的开关,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39845711/

相关文章:

ios - 无法集成 Firebase iOS SDK - 架构 x86_64 : 的 undefined symbol

ios - 如何使 iOS 中 Google map 上的标记在没有动画的情况下改变其位置

Swift 已连接到 SQLite DB,但我找不到该文件

ios - UIView.animate 似乎卡住了其他 View 更新

ios - Amazon Cognito 开发人员使用 iOS SDK 进行身份验证

ios - UIScrollView 损坏并停止使用 OpenGL 渲染滚动(相关 CADisplayLink、NSRunLoop)

iphone - iOS检查 uislider 值是否增加或减少。

iOS 9 黑色键盘破坏布局

ios - 如果我不移动手指,touchesEnded 不会被调用

ios - Soundcloud iframe 不适用于 UIWebView swift