[英]Generics Protocol as Type in Swift
如何創建協議變量。 我的目標是協議將具有一個具有泛型類型的函數,而我使用的是訪問Class
associatedtype
類型,並且該函數將返回泛型類型。 以下示例聲明:
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
是一個將從另一個類繼承的類(重要步驟)。
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>>()
同樣,任何類都是從Component
繼承的,並且變量mComponentFactoryMap
可以使用擴展內部。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.