ios – 子类中的Swift覆盖协议方法

前端之家收集整理的这篇文章主要介绍了ios – 子类中的Swift覆盖协议方法前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一个基类,它实现了一个符合协议的扩展,如下所示:
  1. protocol OptionsDelegate {
  2. func handleSortAndFilter(opt: Options)
  3. }
  4.  
  5. extension BaseViewController: OptionsDelegate {
  6. func handleSortAndFilter(opt: Options) {
  7. print("Base class implementation")
  8. }
  9. }

我有一个继承自BaseViewController的子类“InspirationsViewController”.我在扩展中覆盖协议方法如下:

  1. extension InspirationsViewController {
  2. override func handleSortAndFilter(opt: Options) {
  3. print("Inside inspirations")
  4. }
  5. }

当我在子类扩展中覆盖“handleSortAndFilter”函数时,我收到错误:“扩展中的延迟无法覆盖”

但是当我实现UITableView数据源和委托方法时,我没有看到类似的问题.

如何避免这个错误

解决方法

使用where子句的协议扩展.有用.
  1. class BaseViewController: UIViewController {
  2.  
  3. }
  4.  
  5. extension OptionsDelegate where Self: BaseViewController {
  6. func handleSortAndFilter(opt: Options) {
  7. print("Base class implementation")
  8. }
  9. }
  10.  
  11. extension BaseViewController: OptionsDelegate {
  12.  
  13. }
  14.  
  15. class InsipartionsViewController: BaseViewController {
  16.  
  17. }
  18.  
  19. extension OptionsDelegate where Self: InsipartionsViewController {
  20. func handleSortAndFilter(opt: Options) {
  21. print("Inspirations class implementation")
  22. }
  23. }

猜你在找的iOS相关文章