gpt4 book ai didi

ios - Swift 中的泛型和 ViewModel

转载 作者:行者123 更新时间:2023-12-01 16:20:20 25 4
gpt4 key购买 nike

我正在尝试使用泛型简化以下代码。除了对 ChildViewOne、ChildViewTwo 和 ChildViewThree 中的每个类型进行条件解包之外,我可以使用泛型实现相同的效果吗?

struct UserInfo {
let name: String
let image: UIImage
}

enum SomeType {
case typeOne
case typeTwo
case typeThree
}

struct ParentViewModel {
let userInfo: UserInfo
let type: SomeType

var contentViewModel: Any {
switch type {
case .typeOne:
return ChildViewModelOne(name: userInfo.name, type: type)
case .typeTwo:
return ChildViewModelTwo(image: userInfo.image, type: type)
case .typeThree:
return ChildViewModelThree(image: userInfo.image)
}
}

struct ChildViewModelOne {
let name: String
let type: SomeType
}

struct ChildViewModelTwo {
let image: UIImage
let type: SomeType
}

struct ChildViewModelThree {
let image: UIImage
}

ParentViewController 将被注入(inject) ParentViewModel。
class ParentViewController: UIViewController {
let viewModel: ParentViewModel

init(viewModel: ParentViewModel) {
self.viewModel = viewModel
super.init(bundle: nil, frame: nil)
}

// other required initializer

func configureViewForType() {
// Logic to handle subviews - ChildViewOne, ChildViewTwo & ChildViewThree
}
}

这是我到目前为止所尝试的:
我介绍了一个协议(protocol) ConfigurableView
protocol ConfigurableView {
associatedtype ViewModel
func configure(model: ViewModel)
}

class ChildViewOne: UIView, ConfigurableView {
func configure(model: ChildViewModelOne) {

}

typealias ViewModel = ChildViewModelOne
}

更新

如何从 ParentViewModel 将其返回为 contentViewModel ParentViewModel 中的对象? contentViewModelfunc configureViewForType() 调用里面 ParentViewController其中基于 type ParentViewModel 中的值,我加载了正确的 ChildView
有没有更好的方法来实现这一目标?

最佳答案

View 模型实际上不是“ View 模型”。这个想法很普遍,因为并非所有语言都有嵌套类型。相反,它是 View.Model .

class ChildViewOne: UIView {
struct Model {
let name: String
}

init?(model: Model, coder: NSCoder) {
self.model = model
super.init(coder: coder)
}

private let model: Model

required init?(coder _: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}

关于ios - Swift 中的泛型和 ViewModel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61719155/

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