【问题标题】:BaseViewController & UIPageViewController in SwiftSwift 中的 BaseViewController 和 UIPageViewController
【发布时间】:2019-06-19 09:42:13
【问题描述】:

背景:

我正在设置一个 BaseViewController,它在 Swift 中继承 UIViewController,以便所有其他 ViewController 类继承并采用它的属性。

问题:

但是,当创建一个也继承自 UIPageViewController(和 BaseViewController)的类时,我们有 UIViewController 的继承重叠

这会导致多重继承错误。还有什么其他的建模方法?

试过了:

我已尝试使用协议方法,以便 BasePageViewController 将实现协议 BaseViewController,但是,我找不到将函数放入协议以供 BasePageViewController 继承的方法。另外,我不知道这可能对未来产生什么影响。

任何帮助将不胜感激,谢谢!

class BaseViewController: UIViewController {
    func someFunction(){}
}

class PageBaseViewController: BaseViewController, UIPageViewController {
    //this class overlaps in inheritance to UIViewController
    // Error -> Multiple Inheritance from classes UIPageViewController and BaseViewController
}

【问题讨论】:

  • 您可以扩展 protocol 并将您的逻辑放入函数中。

标签: swift oop protocols


【解决方案1】:

你可以这样写protocol

protocol BaseViewProtocol {
    func someFunction()
}

extension BaseViewProtocol where Self: UIViewController {

    func someFunction() {
      // Logic
    }
}

然后你让你的PageBaseViewController 符合协议。

class PageBaseViewController: UIPageViewController, BaseViewProtocol

现在您的PageBaseViewController 具有函数someFunction,其逻辑在protocol 扩展中声明。

但是,如果您使用的是 Swift 4,我认为这种方法存在一些问题。https://bugs.swift.org/browse/SR-5581

您在 Swift 5 上应该是安全的。

【讨论】:

  • 明白了,谢谢!!
猜你喜欢
  • 1970-01-01
  • 2017-12-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-06-13
  • 2016-12-07
相关资源
最近更新 更多