【问题标题】:Swift ViewModel with associated type for UITableViewCellSwift ViewModel 与 UITableViewCell 的关联类型
【发布时间】:2016-03-20 20:07:01
【问题描述】:

我有以下协议和 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 绑定到 TableViewCell 类。 但我苦苦挣扎的地方是绑定本身:

// 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),我想知道是否有办法直接调用该方法而不使用运行时。

【问题讨论】:

    标签: ios swift uitableview protocols associated-types


    【解决方案1】:

    你想做的实际上没有意义。正如错误所说,您要转换为具有关联类型的协议,并且当前无法在进行转换时提供该类型,并且没有类型,转换的单元格将不知道它可以将哪种类型的对象作为参数对于bind 函数。您应该使用 is 关键字检查您的单元格类型是否为 TVC1TVC2 并转换为该类型。然后你就可以在转换后的引用上调用bind

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-11-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-05-13
      相关资源
      最近更新 更多