ios - 清洁 Swift / VIPER 协议一致性
问题描述
我目前正在研究一个 Clean Swift(类似于 VIPER)的实现。对于每个模块,我都有一个 Presenter 和一个 Displayer(最终是一个 ViewControler),所有这些都基于协议。
这些是我的通用 Displayer 和 Presenter 协议:
// Generic Displayer
protocol BaseDisplayLogic: class {
func displayError(message: String)
func displayApiError(error: ApiError)
}
extension BaseDisplayLogic where Self: UIViewController {
func displayApiError(error: ApiError) {
if let errorDescription = error.errorDescription {
self.warningAlert(errorDescription)
}
}
func displayError(message: String) {
}
}
// Generic Presenter
protocol BasePresentationLogic: class {
var viewController: BaseDisplayLogic? { get }
func presentError(message: String)
func presentApiError(error: ApiError)
}
extension BasePresentationLogic {
func presentError(message: String) {
}
func presentApiError(error: ApiError) {
}
}
这是我需要的模块的实现:
// A displayer
protocol RestorePasswordDisplayLogic: BaseDisplayLogic {
func displayPasswordRestore(ok: Bool)
}
class RestorePasswordViewController: UIViewController {
}
// A presenter
protocol RestorePasswordPresentationLogic: BasePresentationLogic {
func presentPasswordRestore(ok: Bool)
}
class RestorePasswordPresenter: RestorePasswordPresentationLogic {
weak var viewController: RestorePasswordDisplayLogic?
func presentPasswordRestore(ok: Bool) {
self.viewController?.displayPasswordRestore(ok: ok)
}
}
问题是我在 Presenter 实现中遇到错误(在这种情况下为 RestorePasswordPresenter),因为它不符合 BasePresentationLogic 协议。如果我删除
var viewController: BaseDisplayLogic? { get }
它工作得很好,但我需要从 BasePresentationLogic 扩展中看到 viewController var,以便我可以对 presentError 和 presentApiError 方法进行默认实现。
对此有任何想法吗?
解决方案
直接的问题是您没有按照要求遵守协议。你需要一个viewController
type BaseDisplayLogic?
。所以你需要创建它,并将你更具体的版本存储在一个支持变量中:
weak var restorePasswordViewController: RestorePasswordDisplayLogic?
var viewController: BaseDisplayLogic? { restorePasswordViewController }
(就个人而言,并且仅作为一种观点,我认为这是过度使用协议,并且可能是许多令人头疼的问题,特别是如果您尝试使这些部分通用并开始需要类型橡皮擦。如果您成功了有了它,给你更多的权力,但维护所有这些并行的类/协议层次结构对我来说似乎是个坏主意。它正在用协议重新发明类继承,这不是协议的用途,而且它们也不是很擅长。 )
推荐阅读
- c# - 通过 .NET Core 控制台应用迭代地将数据推送到 Azure 搜索索引
- c# - 即使我可以在 VS2019 中构建也无法发布 WPF 应用程序
- qt - 无法单击鼠标区域下方的按钮
- css - 贝宝 iframe 自定义样式
- salesforce - 我是 Apex 开发的新手并尝试编译此代码但失败了
- oracle - 在 oracle xstore pos 中将按钮的颜色更改为红色
- python-3.x - groupby 和聚合在 pyspark 中的 RDD 对象中的多个元素
- arm - 无法在 qemu 中运行无操作功能
- javascript - 如果页面显示为“上一页”,则识别页面?
- linux - 在 @INC 中找不到 File/Slurp.pm