I have a problem with generics in Swift (3):
I get different data of different classes, implementing the same protocol, from server and I need to put them into a class with generics (e.g. Array).
I do not know which class the data will be so I need to use the protocol. So I have following structure:
My protocol:
protocol MyProtocol {
// some protocol stuff
}
Some classes implementing the protocol
class MyProtocolImpl1: MyProtocol{
// some class stuff
}
class MyProtocolImpl2: MyProtocol {
// some class stuff
}
....
class with generic:
final class MyGenericsClass<T: MyProtocol> {
// some class stuff
}
now I want to use this class this way:
func createClass<T>(model: T.Type) -> MyGenericClass<T> {
let myClass = MyGenericClass<T>()
return myClass
}
...
EDIT
func getClass() -> MyProtocol.Type {
return MyProtocolImpl1.self
}
let impl1 = getClass()
let impl2 = MyProtocolImpl2.self
let createdClass = createClass(impl1) //not working
let createdClass = createClass(impl2) //working
doing createClass(impl1)
I get this error:
cannot invoke 'createClass' with an argument list of type '(MyProtocol.Type)'
Changing the MyProtocol to a class would fix the problem but then I could not be sure every class inheriting from it implements the needed methods.
Does someone have some ideas how to solve this problem?