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
...
...
...
}
}
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.
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.
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.
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/
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