Reputation: 1890
I have an array of objects. The array contains different subclasses.
class MainClass {
}
class SubClass1: MainClass{
}
class SubClass2: MainClass{
}
var arrayOfObjects = [SubClass1(), SubClass2(), SubClass1()]
I want to include a function that removes all objects that are a specific subclass type.
arrayOfObjects = arrayOfObjects.compactMap { $0 as? Subclass1 }
How can I use the subclass type as function parameter?
func removeObjectsOf(type: //??) {
arrayOfObjects = arrayOfObjects.compactMap { $0 as? type }
}
Upvotes: 1
Views: 89
Reputation: 51973
You can filter using type(of:)
let filtered = arrayOfObjects.filter { type(of: $0) == SubClass1.self }
or if you want to write it as a function
func filter(_ array: [MainClass], with classType: MainClass.Type) -> [MainClass] {
array.filter { type(of: $0) == classType }
}
filter(arrayOfObjects, with: SubClass1.self)
Upvotes: 3
Reputation: 299345
You can pass this kind of type as a generic type parameter:
func removeObjectsOf<T: MainClass>(type: T.Type) {
arrayOfObjects = arrayOfObjects.compactMap { $0 as? T }
}
Upvotes: 1