我试图将泛型与协议混合使用,但遇到了很大的困难 xD。
我在一个 Android/Java 项目中实现了特定的架构,并尝试对其进行重写以适应 Swift/iOS 项目。但是我发现了这个限制。
ProtocolA
protocol ProtocolA {
}
协议B
protocol ProtocolB : ProtocolA {
}
实现协议A
class ImplementProtocolA <P : ProtocolA> {
let currentProtocol : P
init(currentProtocol : P) {
self.currentProtocol = currentProtocol
}
}
实现协议B
class ImplementProtocolB : ImplementProtocolA<ProtocolB> {
}
因此,当我尝试将ProtocolB设置为实现ProtocolA的具体类型时,我会收到以下错误:
不支持将“ProtocolB”用作符合协议“ProtocolA”的具体类型
1 这种“限制”有什么原因吗?
2 是否有任何解决方法可以实现这个目标?
3 最终是否会支持这种方式?
--已更新--
我认为这是同样问题的另一种变体:
查看协议
protocol View {
}
protocol GetUserView : View {
func showProgress()
func hideProgress()
func showError(message:String)
func showUser(userDemo:UserDemo)
}
演示者协议
protocol Presenter {
typealias V : View
}
class UserDemoPresenter : Presenter {
typealias V = GetUserView
}
错误:
UserDemoPresenter.swift中可能意图匹配的 'V' (也称为 'GetUserView') 不符合 'View'。
这是怎么回事?它符合啊!
即使我使用 View 而不是 GetUserView,它还是无法编译。
class UserDemoPresenter : Presenter {
typealias V = View
}
UserDemoPresenter.swift中可能意图匹配'V'(即'View'),但未符合'View'的要求。
xxDD我真的不明白。
--更新--
使用Rob Napier提出的解决方案并不能解决问题,只是延迟了问题的出现。
当我试图定义对UserDemoPresenter的引用时,需要指定泛型类型,因此我会得到相同的错误:
private var presenter : UserDemoPresenter<GetUserView>
不支持将“GetUserView”用作符合协议“GetUserView”的具体类型。