How to use AS with a switch in swift to get class type

I have an array SomeClassthat is a superclass of other classes.
The array has all of these random classes. Is there a way to use a switch (as opposed to else if let something = elm as? TheSubClassType)

In pseudo code:

for AObjectOfTypeSomeClass in MyBigArray{
  switch the_type_of(AObjectOfTypeSomeClass){
    case SubClass1:
        let O = AObjectOfTypeSomeClass as! SubClass1
    ...
    ...
    ...
  }
}
+4
source share
1 answer

You were close.

for objectOfSomeClass in MyBigArray {
    switch objectOfSomeClass {
    case let subClass as SubClass1:
        // Do what you want with subClass
    default:
        // Object isn't the subclass do something else
    }
}

This site has the best pattern matching statement I've found. http://appventure.me/2015/08/20/swift-pattern-matching-in-detail/

+16
source

Source: https://habr.com/ru/post/1605753/


All Articles