gpt4 book ai didi

swift2 - Swift 2 协议(protocol) - 具有泛型类型的属性?

转载 作者:行者123 更新时间:2023-12-04 23:44:33 26 4
gpt4 key购买 nike

在我使用 Swift 2 的项目中,我正在处理 2 个协议(protocol),MyViewControllerProtocolMyViewModelProtocol .我希望所有 View Controller 都符合 MyViewControllerProtocol .该协议(protocol)将需要一个属性。该属性应符合 MyViewModel协议(protocol)。

我想在这里会起作用的是这样的:

protocol MyViewControllerProtocol {
var viewModel: <T:MyViewModelProtocol> { get set }
}

class MyCustomViewModel: MyViewModelProtocol {
// Implementation here
}

然后对于 View Controller :
class ViewController: UIViewController, MyViewControllerProtocol {
var viewModel: MyCustomViewModel {
// Getter and Setter implementations here
}
}

我很可能在想这个错误。这不会编译,而且我还没有看到这种类型的实现与属性结合使用。是否有其他模式可以完成我在这里尝试做的事情?

最佳答案

如果你想要动态协议(protocol)属性类型,有 typealias .

protocol MyViewModel {
var title: String { get set }
}

protocol MyViewController {
typealias MyViewModelType

var viewModel: MyViewModelType { get set }
}

class BaseViewController<T: MyViewModel>: MyViewController {
typealias MyViewModelType = T
var viewModel: T

init(_ viewModel: T) {
self.viewModel = viewModel
}
}

struct CarViewModel: MyViewModel {
var title: String = "Car"
}

struct BikeViewModel: MyViewModel {
var title: String = "Bike"
}

let car = BaseViewController(CarViewModel())
let bike = BaseViewController(BikeViewModel())

如果您尝试将其与不符合您的 MyViewModel 的模型一起使用协议(protocol),它将不起作用:
struct AnotherModel {
var title: String = "Another"
}

let another = BaseViewController(AnotherModel())

这有一些陷阱,例如您无法通过 MyViewController 的参数传递 View Controller 类型,因为 typealias .这是行不通的:
func something(vc: MyViewController) {
}

为什么不使用更简单的方法而不使用 typealias .如果我理解正确,你就不需要它们。就像是:
protocol MyViewModel {
var title: String { get set }
}

protocol MyViewController {
var viewModel: MyViewModel { get set }
}

class BaseViewController: MyViewController {
var viewModel: MyViewModel

init(_ viewModel: MyViewModel) {
self.viewModel = viewModel
}
}

struct CarViewModel: MyViewModel {
var title: String = "Car"
}

struct BikeViewModel: MyViewModel {
var title: String = "Bike"
}

现在您可以使用 MyViewController协议(protocol)作为变量类型:
let bike: MyViewController = BaseViewController(BikeViewModel())
let car: MyViewController = BaseViewController(CarViewModel())

您可以将它传递给某些函数,如 MyViewController :
func something(vc: MyViewController) {
}

你也不能这样做:
struct AnotherViewModel {
var title: String = "Another"
}

let another: MyViewController = BaseViewController(AnotherViewModel())

我错过了什么?我的意思是,关于你的泛型和类型约束?您是否有一些用例迫使您使用它们?

关于swift2 - Swift 2 协议(protocol) - 具有泛型类型的属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31713868/

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