Ios 清洁Swift/VIPER协议符合性
我目前正在致力于一个干净的Swift(类似于VIPER)实现。对于每个模块,我都有一个演示器和一个显示器(最后是一个ViewControler),所有这些都基于协议 这些是我的通用显示器和演示器协议:Ios 清洁Swift/VIPER协议符合性,ios,swift,Ios,Swift,我目前正在致力于一个干净的Swift(类似于VIPER)实现。对于每个模块,我都有一个演示器和一个显示器(最后是一个ViewControler),所有这些都基于协议 这些是我的通用显示器和演示器协议: // Generic Displayer protocol BaseDisplayLogic: class { func displayError(message: String) func displayApiError(error: ApiError) } extension
// 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 }
它工作得很好,但是我需要viewController变量从BasePresentationLogic扩展可见,这样我就可以对presentError和PresentAppierError方法进行默认实现
有什么想法吗?直接的问题是你没有按照要求遵守协议。您需要类型为
BaseDisplayLogic?
的viewController
。因此,您需要创建它,并将更具体的版本存储在备份变量中:
weak var restorePasswordViewController: RestorePasswordDisplayLogic?
var viewController: BaseDisplayLogic? { restorePasswordViewController }
(就我个人而言,也只是作为一种观点,我认为这是对协议的过度使用,并且可能是许多令人头痛的问题的根源,特别是如果你曾经尝试将这些部分变成通用的,并且开始需要类型擦除器。如果你已经成功地使用了它,你会有更多的能力,但是维护所有这些并行类/协议层次结构对你来说似乎是个坏主意我。这是用协议重新创造类继承,而协议不是用来做什么的,而且它们也不是很擅长。)我部分同意协议过度使用的说法。我从干净的Swift模板开始,并“某种程度上”继承了所有这些东西,但不断尝试改进它……任何建议都将不胜感激:)如果你想了解我关于协议/泛型的建议的简短版本,看看你是否想看到关于避免增加复杂性的架构的讨论,看看Dave DeLong的“更好的MVC”(实际上我非常喜欢演示者作为一个概念。但我认为这些“架构模式”很多如果发现基本假设是错误的,那么将这一伟大的想法埋没在太多层添加的样板文件中是没有帮助的,并且会使以后的重构更加困难。)