Swift generics and subclasses

Viewed 780

my question might be simple, but it got me puzzled a bit: Imagine I have an array of different objects which all have a common parent class "MyClass".

var values = [MyClass]()

However they all have their specific subclass like for example "MyClassSubclass".

values.append(MyClassSubclass())

I now want to create a generic method returning me the first object inside this array which is of type MyClassSubclass. I would like to prevent casting the object, but instead have a generic method which takes the subclass object as T parameter and returns me the first occurrence of subclass T inside this array.

I thought of something like this (but surely that does not work):

func getFirst<T: MyClass>(_ ofType : T.Type) -> T?

I guess I'm just stuck and I don't know what to search for, so if someone could help me I would greatly appreciate it.

Edit Example based on the above values:

class MyClass {}
class MyClassSubclass : MyClass {}
class MyClassSubclass2 : MyClass{}

var values = [MyClass]()
values.append(MyClassSubclass())
values.append(MyClassSubclass2())

//Return the first class element appearing here as a subclass type
func getFirst<T>(_ ofType : T.Type) -> T?{}

Thanks

3 Answers
Related