Swift Generics with Protocol.Type

I have a generic problem in Swift (3):

I get different data from different classes, implementing the same protocol, from the server, and I need to put them in a class with generics (e.g. Array).

I don't know what data class will be, so I need to use a protocol. Therefore, I have the following structure:

My protocol:

protocol MyProtocol {
    // some protocol stuff
}

Some classes that implement the protocol

class MyProtocolImpl1: MyProtocol{
    // some class stuff
}

class MyProtocolImpl2: MyProtocol {
    // some class stuff
}
....

class with common:

final class MyGenericsClass<T: MyProtocol> {
    // some class stuff
}

Now I want to use this class as follows:

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

Execution createClass(impl1)I get this error:

cannot invoke 'createClass' with an argument list of type '(MyProtocol.Type)'

Changing MyProtocol for the class would fix the problem, but then I couldnโ€™t be sure that every class that inherits from it implements the necessary methods.

Does anyone have any ideas how to solve this problem?

+4
2

, . MyProtocol.self , ergo MyProtocol. MyProtocol, T, T: MyProtocol.

; , doFoo() MyProtocol, GenericClass<MyProtocol> MyProtocol.doFoo() , ? , MyProtocol (.. , ), .


:

, , ClassA ClassB ClassX. , MyProtocol

. " MyProtocol" , MyProtocol .


? AnyObject, MyGenericClass<T>, T.

extension MyProtocol
{
    static func createMyGenericClass() -> AnyObject
    {
        return MyGenericClass<Self>()
    }
}

func createClass(_ modelType: MyProtocol.Type) -> AnyObject
{
    return modelType.createMyGenericClass()
}

MyGenericClass MyProtocol.Type. , MyProtocol.

+1

, , , , .

import Foundation


protocol MyProtocol {
}

class ClassA : MyProtocol {
}

class ClassB : MyProtocol {
}

final class GenericClass<T:MyProtocol> {

}

func createClass<T:MyProtocol>(_ model: T.Type) -> GenericClass<T> {
    let myClass = GenericClass<T>()
    return myClass
}
let createdClass = createClass(ClassA.self)
0

Source: https://habr.com/ru/post/1665892/


All Articles