gpt4 book ai didi

ios - Swift ViewModel 与 UITableViewCell 的关联类型

转载 作者:行者123 更新时间:2023-11-30 13:35:31 26 4
gpt4 key购买 nike

我有以下协议(protocol)和 ViewModel

class ViewModel1 {}
class ViewModel2 {}

protocol CellViewModelType {
typealias ViewModel
func bind(vm:ViewModel)
}

class TVC1 : UITableViewCell, CellViewModelType {
typealias ViewModel = ViewModel1
func bind(vm:ViewModel)
}

class TVC2 : UITableViewCell, CellViewModelType {
typealias ViewModel = ViewModel2
func bind(vm:ViewModel)
}

此设置允许我将 ViewModel 绑定(bind)到 TableViewCell 类。但我遇到的困难是绑定(bind)本身:

// error: Protocol 'CellViewModelType' can only be used as a generic constraint because it has Self or associated type requirements
let cell = tableView.dequeueReusableCellWithIdentifier(item.0, forIndexPath: indexPath) as! CellViewModelType
cell.bind(someViewModelReference)

到目前为止,我想到的唯一解决方法是使用动态调度(performSelector),我想知道是否有一种方法可以直接调用该方法而不使用运行时。

最佳答案

你想做的事情实际上没有意义。由于错误表明您想要转换为具有关联类型的协议(protocol),并且目前无法在进行转换时提供该类型,并且如果没有类型,转换的单元将不知道它可以将什么类型的对象作为参数用于bind 函数。您应该使用 is 关键字检查您的单元格类型是否为 TVC1TVC2 并强制转换为该类型。然后,您只需对转换的引用调用 bind 即可。

关于ios - Swift ViewModel 与 UITableViewCell 的关联类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36118859/

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