I want to do this with a switch:
protocol TestProtocol {}
class A: TestProtocol {}
class B: TestProtocol {}
var randomObject: TestProtocol
if let classAObj = randomObject as? A {
} else if let classBObj = randomObject as? B {}
I want something like this:
switch randomObject {
case let classAObj = randomObject as? A:
...
case let classBObj = randomObject as? B:
....
default:
fatalError("not implemented")
}
Sure you can:
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")
}
In a pattern matching expression it is as
, not as?
,
and = randomObject
is not needed, the value to match is given
right after the switch
keyword.
And just for the sake of completeness: Pattern matching with
case let
can also be used in if-statements (or while/for-statements):
if case let classAObj as A = randomObject {
} else if case let classBObj as B = randomObject {
}
However in this case there would be no reason to do so.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With