Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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
    ...
    ...
    ...
  }
}
like image 564
Itay Moav -Malimovka Avatar asked Sep 03 '15 14:09

Itay Moav -Malimovka


People also ask

What is as in Swift?

Operator. Prior to Swift 1.2, the as operator could be used to carry out two different kinds of conversion, depending on the type of expression being converted and the type it was being converted to: Guaranteed conversion of a value of one type to another, whose success can be verified by the Swift compiler.

How do switch statements work Swift?

The switch statement in Swift lets you inspect a value and match it with a number of cases. It's particularly effective for taking concise decisions based on one variable that can contain a number of possible values. Using the switch statement often results in more concise code that's easier to read.

Is break needed in Swift switch?

Although break isn't required in Swift, you can use a break statement to match and ignore a particular case or to break out of a matched case before that case has completed its execution. For details, see Break in a Switch Statement. The body of each case must contain at least one executable statement.


1 Answers

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/

like image 103
Mr Beardsley Avatar answered Sep 21 '22 13:09

Mr Beardsley