In Swift how can I filter an array of objects conforming to a protocol by their class?

I would use compactMap instead of filter here in order to give you better type safety. You can use a conditional downcast to filter out the elements you want and generics in order to preserve type information. This takes advantage of the fact that compactMap can filter out nil results from the transform function.

let array: [VariousThings] = [ThingType1(), ThingType2()]    

func itemsMatchingType<T : VariousThings>(_ type: T.Type) -> [T] {
  return array.compactMap { $0 as? T }
}

let justThingTypes1 = itemsMatchingType(ThingType1.self) // of type [ThingType1]

Now the array you get out of your itemsMatchingType function is [ThingType1] if you pass in ThingType1, rather than simply [VariousThings]. That way you don't have to deal with ugly forced downcasts later down the line.


You could use a generic

func itemsMatchingType<T : VariousThings>(type: T.Type) -> [VariousThings] {
  return array.filter { $0 is T }
}

You can use the filter for this:

let justThingsTypes1 = array.filter { $0 is ThingType1 }