【问题标题】:self constraint protocol extention for UIViewControllerUIViewController 的自约束协议扩展
【发布时间】:2017-08-10 12:41:18
【问题描述】:

我正在处理一个遗留的 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

【问题讨论】:

  • 尝试从您的NewViewController 中删除SuccessPresenting 一致性约束。即class NewViewController: UIViewController { // code that calls presentSuccess }
  • @NandiinBao 这对我也没有帮助

标签: swift swift2 swift-protocols


【解决方案1】:

这是直接粘贴吗?因为您的extension 包含一个可选字符串而不是常规字符串,而您的协议有一个普通的String。这可能会导致编译器认为它是一种不同的方法,从而在这种特殊情况下使您的协议的optionallness 无效。

【讨论】:

  • 哦,感谢上帝 stackOverFlow 的存在。当然,你是对的,我不专心)
猜你喜欢
  • 1970-01-01
  • 2016-04-30
  • 1970-01-01
  • 1970-01-01
  • 2015-09-16
  • 1970-01-01
  • 2021-12-16
  • 2016-07-29
  • 1970-01-01
相关资源
最近更新 更多