13

I have an array of SomeClass which is the super class of various other classes.
The array has all of those random classes in it.
Is there a way using 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
    ...
    ...
    ...
  }
}
Itay Moav -Malimovka
  • 52,579
  • 61
  • 190
  • 278

1 Answers1

36

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 rundown of pattern matching I have found. http://appventure.me/2015/08/20/swift-pattern-matching-in-detail/

Mr Beardsley
  • 3,743
  • 22
  • 28
  • I see how it works, but logically I do not understand some thing with this syntax. For example, how come the `as` is not optional? – Itay Moav -Malimovka Sep 03 '15 at 14:59
  • 2
    The as is not optional because you are pattern matching, not binding. Binding would look like this and requires the optional cast: if let subClass = anObject as? SubClass { } . I admit it is somewhat counter intuitive since they both accomplish similar goals. – Mr Beardsley Sep 03 '15 at 15:22
  • @Itay: For `as` vs `as?` in a case statement compare http://stackoverflow.com/questions/31759778/need-clarification-of-type-casting-operator-in-swift. – Martin R Sep 03 '15 at 16:59