Swift 中的泛型协议类型
Generics Protocol as Type in Swift
如何创建协议变量。我的目标是协议将具有泛型类型的函数,我正在使用 associatedtype
访问 Class
并且函数将是 return 泛型类型。示例声明如下:
public protocol ComponentFactory {
associatedtype T // A class and that class can be inherit from another so I need define generic type here
func create() -> T
}
我想像这样为这个协议声明一个变量:
fileprivate var mComponentFactoryMap = Dictionary<String, ComponentFactory>()
在这一行我收到一个错误:
Protocol 'ComponentFactory' can only be used as a generic constraint because it has Self or associated type requirements
我从 Android 看到,实际上从 kotlin 他们有一个 interface
的声明,例如:
private val mComponentFactoryMap = mutableMapOf<String, ComponentFactory<*>>()
任何人都可以帮助我,我如何从 Swift 声明这个?
几个月前我已经通过下面的描述解决了这个问题。请检查它,如果有请给我另一个解决方案。
首先,为 Protocol
做一些改变。在 associatedtype T
处应更改为 associatedtype Component
,而 Component
是一个 class,它将继承自另一个 class(重要步骤)。
public protocol ProComponentFactory {
associatedtype Component
func create() -> Component?
}
其次,我将创建一个继承自 ProComponentFactory
的 Generic Struct
:
public struct ComponentFactory<T>: ProComponentFactory {
public typealias Component = T
public func create() -> T? { return T.self as? T }
}
干得好,现在你可以定义一个变量,就像我在上面的问题中举的例子:
fileprivate var mComponentFactoryMap = Dictionary<String, ComponentFactory<Component>>()
以及任何 class 继承自 Component
并且变量 mComponentFactoryMap
可以在内部使用扩展。
如何创建协议变量。我的目标是协议将具有泛型类型的函数,我正在使用 associatedtype
访问 Class
并且函数将是 return 泛型类型。示例声明如下:
public protocol ComponentFactory {
associatedtype T // A class and that class can be inherit from another so I need define generic type here
func create() -> T
}
我想像这样为这个协议声明一个变量:
fileprivate var mComponentFactoryMap = Dictionary<String, ComponentFactory>()
在这一行我收到一个错误:
Protocol 'ComponentFactory' can only be used as a generic constraint because it has Self or associated type requirements
我从 Android 看到,实际上从 kotlin 他们有一个 interface
的声明,例如:
private val mComponentFactoryMap = mutableMapOf<String, ComponentFactory<*>>()
任何人都可以帮助我,我如何从 Swift 声明这个?
几个月前我已经通过下面的描述解决了这个问题。请检查它,如果有请给我另一个解决方案。
首先,为 Protocol
做一些改变。在 associatedtype T
处应更改为 associatedtype Component
,而 Component
是一个 class,它将继承自另一个 class(重要步骤)。
public protocol ProComponentFactory {
associatedtype Component
func create() -> Component?
}
其次,我将创建一个继承自 ProComponentFactory
的 Generic Struct
:
public struct ComponentFactory<T>: ProComponentFactory {
public typealias Component = T
public func create() -> T? { return T.self as? T }
}
干得好,现在你可以定义一个变量,就像我在上面的问题中举的例子:
fileprivate var mComponentFactoryMap = Dictionary<String, ComponentFactory<Component>>()
以及任何 class 继承自 Component
并且变量 mComponentFactoryMap
可以在内部使用扩展。