gpt4 book ai didi

Swift 泛型 : parameters cyclic dependencies resolution

转载 作者:行者123 更新时间:2023-11-28 08:02:57 25 4
gpt4 key购买 nike

很抱歉,如果这不是一个足够具体的问题,但是你能建议一些方法来解决泛型参数循环依赖吗?

我有两种类型:

typealias RiskListPresenter = ListPresenter<RiskListViewController, ...> // <View: ListViewType (generic protocol)>

typealias RiskListViewController = SectionedListViewController<RiskListPresenter, ...> // <Presenter: ListPresenterType (generic protocol), ...>

问题是,Presenter 需要知道 View 的类型才能调用方法来填充它,而 ViewController 需要知道 Presenter 的类型才能实例化它。

我尝试了依赖注入(inject)库 Dip,但无法注入(inject)通用类型。也许还有其他一些技术?

最佳答案

所以我通过消除持有实际类型的必要性,仅用非通用协议(protocol)替换它来解决这个问题。

所以,

ListViewController 中,我将 presenter 作为附加的非通用 protocol ListViewPresenterType 保存,它只能执行我在这里想要的操作。

ListViewController 中的泛型方法将其作为必需的泛型类型启动,使其符合具有所有必要约束的泛型协议(protocol)。

func configure<Presenter: ListPresenterType>(..., presenterType: Presenter.Type, ...) where <all the necessary constraints>
{
presenter = Presenter(dispatcher: dispatcher, view: self as! Presenter.View)
...
}

这样一来,我就能够从 ListViewController 的通用参数中删除 Presenter

有点 hack,但解决了我的问题,我仍然需要这个 configure(...) 方法。

不过,这并不是一个真正的通用解决方案。

关于Swift 泛型 : parameters cyclic dependencies resolution,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46086455/

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