This one has been bugging me for a while now. I'm not sure if I'm missing something, but shouldn't this work?
protocol IDIdentifiable { }
class A : IDIdentifiable {
let id : Int
init(id: Int) { self.id = id }
}
class B : IDIdentifiable {
let id : Int
init(id: Int) { self.id = id }
}
func findObjectById<T: IDIdentifiable>(objects: [T], id: Int) -> T {
if let casted = objects as? [A] {
return casted.filter{ $0.id == id }[0]
}
}
The error happens when casting the objects parameter to an array of A-objects. The error says 'A' is not a subtype of 'T'
, which is obviously not the case.
It's really annoying since I would like to have a generic method that can handle arrays of objects of multiple classes the same way. I tried first without creating an extra protocol like IDIdentifiable, using switch-statements, but none of these approaches worked.
I'm happy for any suggestions!