gpt4 book ai didi

swift - 如何声明泛型基类?

转载 作者:行者123 更新时间:2023-11-28 13:47:46 24 4
gpt4 key购买 nike

我有一个案例是:

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

我需要将基类设为通用类型而不是 UIViewController .

在某些时候,我需要它是 UIViewController , UITableViewController ..等等

例如:

我的基类

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> { }

If we thought it was a kind of UIViewController its works normally

我的BController

class BController : BaseMvpController <AView, APresenter> { }

If we thought it was a kind of UITableViewController, This is case I can not override numberOfItemInRaw and dequeCell ...etc , because base controller inherit from UIViewController

我想让 Base Controller 与所有 Controller ( UIViewControllerUITableViewControllerUICollectionViewController .. 等)一起工作。

我该怎么做

最佳答案

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

例如,

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

关于swift - 如何声明泛型基类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55196260/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com