gpt4 book ai didi

ios - Clean Swift/VIPER 协议(protocol)一致性

转载 作者:行者123 更新时间:2023-11-28 05:36:00 25 4
gpt4 key购买 nike

我目前正在研究 Clean Swift(类似于 VIPER)的实现。对于每个模块,我都有一个 Presenter 和一个 Displayer(最后是一个 ViewControler),所有这些都基于协议(protocol)。

这些是我的通用 Displayer 和 Presenter 协议(protocol):

// 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 协议(protocol)。如果我删除

var viewController: BaseDisplayLogic? { get }

它工作得很好,但我需要 viewController var 从 BasePresentationLogic 扩展可见,这样我就可以默认实现 presentError 和 presentApiError 方法。

有什么想法吗?

最佳答案

直接的问题是您没有按照要求遵守协议(protocol)。您需要 BaseDisplayLogic? 类型的 viewController。因此,您需要创建它,并将更具体的版本存储在支持变量中:

weak var restorePasswordViewController: RestorePasswordDisplayLogic?
var viewController: BaseDisplayLogic? { restorePasswordViewController }

(就个人而言,仅作为一种意见,我认为这是过度使用协议(protocol),并且可能会成为许多令人头疼的问题的根源,尤其是当您尝试使这些部分通用并开始需要类型删除器时。如果您我已经成功了,对你来说更强大了,但是维护所有这些并行的类/协议(protocol)层次结构对我来说似乎是个坏主意。它正在用协议(protocol) reshape 类继承,这不是协议(protocol)的目的,而且它们不是很好在它。)

关于ios - Clean Swift/VIPER 协议(protocol)一致性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58606836/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com