gpt4 book ai didi

ios - Swift 中泛型类型的工厂(协议(protocol)和泛型)

转载 作者:搜寻专家 更新时间:2023-10-30 22:15:19 25 4
gpt4 key购买 nike

我正在尝试创建一个实现协议(protocol)的通用类型工厂。问题是在适配器工厂的 make 方法中出现以下错误:Protocol 'Adapter' can only be used as a generic constraint because it has Self or associated type requirements.

这是我现在正在做的一个例子:

protocol Adapter {

typealias T

static func method1(parameter: T)
}

final class AdapterFactory<T>: NSObject {

static func make(name: String = "") -> Adapter.Type {

switch name {

case "Adapter1":
return ConcreteAdapter1<T>.self

default:
return ConcreteAdapter2<T>.self
}

}
}

final class ConcreteAdapter1<T>: NSObject, Adapter {

static func method1(parameter: T) {
// bla, bla, bla
}
}

最佳答案

您可以使用 swift 标准库中使用的模式(参见 Sequence 和 AnySequence),即使用 AnyAdapter 之类的东西,通过将每个方法调用委托(delegate)给底层实现(适配器协议(protocol)的具体实现,如 ConcreteAdapter1)或通过使用闭包。

然后您的工厂将返回 AnyAdapter 而不是 Adapter。乍一看似乎不自然,但使用 AnyAdapter 作为类型提供与使用协议(protocol)相同的优势(显然这是一种变通方法),因为 AnyAdapter 本身不是具体实现,而是将实现委托(delegate)给具体实现。

这是代码

protocol Adapter {

typealias Element

func method1(parameter: Element)

func method2(parameter : Element)
}




struct AnyAdapter<Element> : Adapter {

private let _method1 : (Element) -> ()

private let _method2 : (Element) -> ()


init<A:Adapter where A.Element == Element>(_ base:A) {
_method1 = { base.method1($0) }
_method2 = { base.method2($0) }
}

func method1(parameter: Element) {
_method1(parameter)
}

func method2(parameter: Element) {
_method2(parameter)
}

}



final class ConcreteAdapter1<T>: NSObject, Adapter {

func method1(parameter: T) {
print("Concrete Adapter 1 method 1")
}

func method2(parameter: T) {
print("Concrete Adapter 1 method 2")
}
}



final class ConcreteAdapter2<T> : Adapter {
func method1(parameter: T) {
print("Concrete adapter 2 method 1")
}

func method2(parameter: T) {
print("Concrete Adapter 2 method 2")
}
}

final class AdapterFactory<T>: NSObject {

static func make(name: String = "") -> AnyAdapter<String> {

switch name {


case "Adapter1":
let concreteAdapter1 = ConcreteAdapter1<String>()
return AnyAdapter(concreteAdapter1)

default:
let concreteAdapter2 = ConcreteAdapter2<String>()
return AnyAdapter(concreteAdapter2)
}

}
}

我没有在协议(protocol)中使用静态方法来简化事情,因为静态方法不能很好地处理泛型类型。

老实说,这是该语言的一个缺点,我希望它能像在 Java 或 C# 中一样简化。

希望这对您有所帮助。

关于ios - Swift 中泛型类型的工厂(协议(protocol)和泛型),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31710065/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com