【发布时间】:2015-11-03 15:59:44
【问题描述】:
我正在尝试将泛型与协议混合使用,但我真的很难 xD
我在一个 Android/Java 项目中实现了某些架构,我正在尝试重写它以适应 swift/iOS 项目。但我发现了这个限制。
协议A
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”(又名“视图”) 不符合“视图”
xxDD 我不明白,真的。
--已更新--
使用 Rob Napier 提出的解决方案,问题并没有得到解决,而是被延迟了。
当尝试定义对 UserDemoPresenter 的引用时,我需要指定泛型类型,所以我得到了同样的错误:
private var presenter : UserDemoPresenter<GetUserView>
使用 'GetUserView' 作为符合协议的具体类型 不支持“GetUserView”
【问题讨论】: