What is best way in swift to get objects of specific type. e.g
protocol Fruit {
func setColor()
}
class Orange:NSObject, Fruit {
func setColor() {
}
}
class Apple:NSObject, Fruit {
func setColor() {
}
}
class MyClass {
var fruits:[Fruit]? // get from data base
//here how to get fruits only of type Orange. i.e. Array of oranges
}
Here one way is I can put "for in" loop and check type of each object and then can add it in new array.
But is there any other swifty way to do?
EDIT:
Below works for me. Is there any other way to do?
var oranges: [Orange] = []
for orange in fruits {
if let myOrange = orange as? Orange {
oranges.append(myOrange)
}
}
fruit in fruitsand thenif let orange = fruit as? Orange {var oranges: [Orange] { return fruits.flatMap{$0 as? Orange} }