SwiftedMind
SwiftedMind

Reputation: 4287

Swift - Check if object is of a given type (where the type has been passed as function argument)

so I have an array full of objects that all inherit from a base class MyBaseClass. Say, there are these subclasses:

SubclassA : MyBaseClass
SubclassB : MyBaseClass
SubclassC : MyBaseClass
SubclassD : MyBaseClass

Now I want a function to filter the array and only include objects that are type of a given subclass:

func myFilter<T: MyBaseClass>(objectType: T.Type) -> [MyBaseClass] {
   ...
   for object in myArray {
       // include, if object is of type `objectType`
   }

   return filteredArray
}


// Example call (that's what I think how it should be called)
let filteredArray = myFilter(objectType: SubclassD.self)

How do I do this? I tried:

object is objectType // XCode: "Use of undeclared type itemType"
type(of: object) == objectType // returns always false, as it doesn't check for subclasses I think
object as objectType // XCode: "Use of undeclared type itemType"

This usually works when I want to check for Int, String or whatever. But it's not working here. Am I doing something wrong or do I misunderstand some concepts?

Any help is appreciated! Thanks

Upvotes: 0

Views: 461

Answers (1)

kiwisip
kiwisip

Reputation: 447

I don't know where you are taking myArray. You probably need to create an extension to Array for MyBaseClass. Like this:

extension Array where Element: MyBaseClass {
  func myFilter<T: MyBaseClass>(objectType: T.Type) -> [T] {
    var filteredArray: [T] = []
    for object in self {
      if let object = object as? T {
        filteredArray.append(object)
      }
    }

    return filteredArray
  }
}

Then you can call:

// Example call
let array = [SubclassA(), SubclassA(), SubclassC(), SubclassD()]
array.myFilter(objectType: SubclassD.self) // == [SubclassD()]

EDIT: Easy solution if you want a return type of myFilter to be just MyBaseClass and you don't want to change the original array would be this:

array.filter { $0 is SubclassD }

Upvotes: 1

Related Questions