我想用一个开关来做到这一点:
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/