簡體   English   中英

Swift中泛型協議的類型

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM