首页 > 解决方案 > 清洁 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 方法进行默认实现。

对此有任何想法吗?

标签: iosswift

解决方案


直接的问题是您没有按照要求遵守协议。你需要一个viewControllertype BaseDisplayLogic?。所以你需要创建它,并将你更具体的版本存储在一个支持变量中:

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

(就个人而言,并且仅作为一种观点,我认为这是过度使用协议,并且可能是许多令人头疼的问题,特别是如果您尝试使这些部分通用并开始需要类型橡皮擦。如果您成功了有了它,给你更多的权力,但维护所有这些并行的类/协议层次结构对我来说似乎是个坏主意。它正在用协议重新发明类继承,这不是协议的用途,而且它们也不是很擅长。 )


推荐阅读