如何声明通用基类?

时间:2019-03-16 11:30:50

标签: swift generics uiviewcontroller

我有一个情况是

class BaseMvpController<V, P: BasePresenter>: UIViewController { }

我需要使基类成为通用类型,而不是UIViewController

在某个时候,我需要它是UIViewController , UITableViewController ..etc

例如:

我的基础课

class BaseMvpController<V, P: BasePresenter>: UIViewController  {
    typealias View = V
    private(set) var presenter: P!
    // MARK: - Initializers

    required public init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }

    override public init(nibName: String?, bundle: Bundle?) {
        super.init(nibName: nibName, bundle: bundle)
    }

    deinit {
        guard let view = self as? P.View else {return}
        if let presenter = presenter {
            presenter.detachView(view)
        }
    }


    // MARK: - Lifecycle

    override func viewDidLoad() {
        super.viewDidLoad()
        presenter = createPresenter()
    }

    override func viewWillAppear(_ animated: Bool) {
        guard let view = self as? P.View else {
            preconditionFailure("MVP ViewController must implement the view protocol `\(View.self)`!")
        }

        super.viewWillAppear(animated)

        if !presenter.isAttached {
            presenter.attachView(view)
        }
    }
    // MARK: - MVP

    /// Override and return a presenter in a subclass.
    func createPresenter() -> P {
        preconditionFailure("MVP method `createPresenter()` must be override in a subclass and do not call `super.createPresenter()`!")
    }

}

我的 AController

class AController : BaseMvpController <AView, APresenter> { }

  

如果我们认为这是一种UIViewController,它可以正常工作

我的 BController

class BController : BaseMvpController <AView, APresenter> { }

  

如果我们认为它是UITableViewController的一种,那么这种情况下我无法覆盖numberOfItemInRaw和dequeCell ... etc,因为基本控制器继承自UIViewController

我想使Base控制器与所有控制器(UIViewControllerUITableViewControllerUICollectionViewController等)一起工作。

我该怎么做

1 个答案:

答案 0 :(得分:1)

您可以在另一个类中“隐藏”泛型。

例如,

class Generic<T, U> { }
class BV: UIViewController {
    var generic: Generic<Int, String>? = nil
}