如何定义一个可以快速保存通用协议类型的变量?

时间:2019-02-04 14:27:08

标签: ios swift generics swift-protocols

我想创建一个方法,该方法采用实现通用协议的类的类型,然后将该值保存在变量中,以便以后可以创建实例。

具有非通用协议的示例

protocol Initializable { init() }

class Impl: Initializable { required init(){} }

//Here we will hold the type of a class that implements Initializable
var initializableType: Initializable.Type? = nil

//This method will get the type of a class that implements Initializable and store it to initializableType.
func register<T>(implementation: T.Type) where T : Initializable {
    initializableType = implementation.self
}

//Register the type
register(implementation: Impl.self)

//Then create instance
initializableType?.init()

现在如何为以下协议做同样的事情?

protocol GenericInitializable {
    associatedtype InitDataType

    init(_ with: InitDataType)
}

似乎我无法定义将包含通用协议的元类型的类型。类型擦除技术适用于实例,顾名思义,它会擦除​​我需要的类型信息。

0 个答案:

没有答案