【发布时间】:2018-11-09 21:53:43
【问题描述】:
我有一个泛型协议TwoWayBindDelegate,它使用泛型关联类型来确定函数twoWayBind()的参数
protocol TwoWayBindDelegate: class {
associatedtype BindType
func twoWayBind(to observable: Observable<BindType>?, observableChanged: ((BindType) -> ())?)
}
然后我创建了一个类Reactive<Base: UIView, Type>(符合TwoWayBindDelegate),您必须在其中使用通用Base 对其进行初始化。例如:let reactiveSlider = Reacive<UISlider>(slider)。
我的问题是,当我扩展 Reactive 并符合 TwoWayBindDelegate 时,我收到错误 Invalid redeclaration of 'BindType',因为我在两个扩展中都声明了 BindType 和 twoWayBind()。有没有办法让两个扩展都为TwoWayBindDelegate 提供不同的实现
class Reactive<Base: UIView>: TwoWayBindDelegate {
public var base: Base
init(base: Base) {
self.base = base
}
}
extension Reactive where Base == UISlider {
typealias BindType = Float
func twoWayBind(to observable: Observable<Float>?, observableChanged: ((Float) -> ())?) {
// implement two way bind for UISlider
}
}
extension Reactive where Base == UITextField {
typealias BindType = String
func twoWayBind(to observable: Observable<String>?, observableChanged: ((String) -> ())?) {
// implement two way bind for UITextField
}
}
我做了一些研究,发现这可能是一个错误https://bugs.swift.org/browse/SR-5392。有没有办法解决
【问题讨论】:
-
我正在使用
BindType,因此twoWayBind()中的参数可以是BindType类型。因此,如果BindType是字符串,则参数将是 Observable。如果我摆脱关联的类型,协议函数的参数将是什么类型?我对泛型没有太多经验,所以如果我错了,我会纠正我。 -
在我看来,你倒退了。如果你在声明中说
Observable<String>,我们知道 BindType 必须是String;泛型已解决。请参阅下面的答案,如果我错了,请纠正我。