gpt4 book ai didi

ios - 如何在 Swift 的泛型中声明基类?

转载 作者:搜寻专家 更新时间:2023-10-31 22:24:26 26 4
gpt4 key购买 nike

代码示例不起作用,但我希望它能成功编译。下面的源代码中很好地描述了想法。您可以轻松地将其粘贴到 Swift playground 中。

import UIKit

// MARK: - Base classes with generics

class FlowController {

}

class ViewModel<FlowControllerType: FlowController> {
let flowController: FlowControllerType
init (flowController: FlowControllerType) {
self.flowController = flowController
}
}

class ViewController<ViewModelType: ViewModel<FlowController>> {

var viewModel: ViewModelType!
}

// MARK: - My implementation

class MyFlowController: FlowController {

}

class MyViewModel: ViewModel<MyFlowController> {
override init (flowController: MyFlowController) {
super.init(flowController: flowController)
}
}

// ERROR: 'ViewController' requires that 'MyModelView' inherit from 'ViewModel<FlowController>'
class MyViewController: ViewController<MyViewModel> {

}

// MARK: - Code

let viewController = MyViewController()
viewController.viewModel = MyViewModel(flowController: MyFlowController())

问题是我想声明 MyViewController,但我得到错误:

'ViewController' requires that 'MyModelView' inherit from 'ViewModel<FlowController>'

问题是如何声明这些类使其工作?我应该为此使用 where 子句吗?我想在基类中拥有自己的 ViewController.viewModelViewModel.flowController 类型,以保持类之间的这些依赖关系。提前谢谢你。

相关问题: Swift generic inheritance

最佳答案

我可能有答案,但它看起来可能比这个解决方案更好。技巧在下一行

class ViewController<FlowControllerType: FlowController, ViewModelType: ViewModel<FlowControllerType>> {

应该用哪个代替

class ViewController<ViewModelType: ViewModel<FlowController>> {

我希望其他人会做得更好,但目前只有这个有效。完整的 Playground 示例:

import UIKit

// MARK: - Base classes with generics

class FlowController {

}

class ViewModel<FlowControllerType: FlowController> {
let flowController: FlowControllerType
init (flowController: FlowControllerType) {
self.flowController = flowController
}
}

class ViewController<FlowControllerType: FlowController, ViewModelType: ViewModel<FlowControllerType>> {

var viewModel: ViewModelType!
}

// MARK: - My implementation

class MyFlowController: FlowController {

}

class MyViewModel: ViewModel<MyFlowController> {
override init (flowController: MyFlowController) {
super.init(flowController: flowController)
}
}

class MyViewController: ViewController<MyFlowController, MyViewModel> {

}

// MARK: - Code

let viewController = MyViewController()
viewController.viewModel = MyViewModel(flowController: MyFlowController())

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

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