UIViewController 的自我约束协议扩展



我正在做一个遗留的 Swift 2.2 项目,我想在我的代码中实现一些众所周知的面向协议的实践。

protocol SuccessPresenting {
func presentSucess(title: String, message: String)
}
extension SuccessPresenting where Self: UIViewController {
func presentSucess(title: String?, message: String) {
let alertController = UIAlertController(title: title, message: message, preferredStyle: .Alert)
let dismissAction = UIAlertAction(title: "ОК", style: .Default, handler: nil)
alertController.addAction(dismissAction)
self.presentViewController(alertController, animated: true, completion: nil)
}
}
class NewViewController: UIViewController, SuccessPresenting {
func foo() {
presentSucess(nil, message: "Done!")
}
}

虽然,它适用于 Swift 3.1,但这里我得到一个错误:The NewViewController doesn't conform to protocol SuccessPresenting

但是我为什么要在我的VC中编写协议实现,因为我已经使用协议扩展完成了呢? 我将不胜感激任何帮助。 请注意,这是 Swift 2.2

这是直接粘贴吗?因为您的extension包含可选字符串而不是常规字符串,而您的协议具有正常的String。这可能会导致编译器将其视为不同的方法,从而使协议的optionallness在这种特定情况下无效。

最新更新