【发布时间】:2022-03-03 19:34:23
【问题描述】:
我正在尝试使用协议来实现 MVP,
我有 View 控制器,它包含对演示者协议的引用。
演示者协议包含对视图的引用
并具有代表 ResultType 的 associatedtype。
每个演示者的 ResultType 都不同。
例如:
class PresenterA: PresenterProtocol {
weak var view: ViewController!
typealias ResultType = String
var onDidPressCallback: ((ResultType) -> Void)?
}
也可以
class PresenterB: PresenterProtocol {
weak var view: ViewController!
typealias ResultType = Apple
var onDidPressCallback: ((ResultType) -> Void)?
}
当我持有对演示者的引用时,问题就开始了 来自 ViewController。
class ViewController: UIViewController {
var presenter: PresenterProtocol!
}
当然这是不可能的,我得到了这个错误:
Protocol 'PresenterProtocol' 只能用作通用约束 因为它有 Self 或关联的类型要求
所以我尝试了:
class ViewController<T: PresenterProtocol>: UIViewController {
var presenter: T!
}
但是现在 PresenterProtocol 有这个问题:
对泛型“ViewController”的引用需要 <...>
中的参数
我做错了什么?我该如何解决?
另外,假设我不支持新版本,所以我不能使用不透明类型(某些关键字)。
【问题讨论】:
-
从你的描述来看,
PresenterProtocol只是对视图的引用,那你为什么要把它放在视图本身呢?视图可能应该有对演示者输出的引用,更像是委托模式。