【问题标题】:Swift workaround for protocols comparison用于协议比较的 Swift 解决方法
【发布时间】:2021-12-30 02:02:40
【问题描述】:

我知道比较协议没有任何意义,但我的情况取决于我之前做出的选择和决定。 表格视图的数据源是一个 RowViewModel 数组。

protocol RowViewModel {}

那里(还)没有任何东西使它甚至符合 Equatable。 然后我的表格有不同的单元格,所有这些单元格都实现了该协议:

func getCells() -> [RowViewModel] {
    var rows = [RowViewModel]()
    rows.append(Cell1ViewModel())
    rows.append(Cell2ViewModel())
    rows.append(Cell3ViewModel())

    return rows
}

Cell 的视图模型:

class Cell1ViewModel: RowViewModel {
    var cellTitle: String
    ...
}

这种结构很方便,但它现在让我很反感,因为我现在需要计算 delta 来发送特定的 tableView 索引来插入/删除行。要计算增量,我需要 RowViewModel 符合 Equatable,这是可能的,但似乎是一种解决方法,它违背了使用这种方法的初始点。我想做这样的事情:

let oldList = rows
let newList = getCells()

let deltaAdded = newList.filter { !oldList.contains($0) }.compactMap { newList.firstIndex(of: $0) }
let deltaRemoved = oldList.filter { !newList.contains($0) }.compactMap { oldList.firstIndex(of: $0) }

这里的最佳做法是什么?有没有办法为符合 RowViewModel 的具体类型编写比较函数?

【问题讨论】:

  • “违背了使用这种方法的初始点”,但重点似乎是这是一个可以包含任何内容的表格视图。一行可以是一行字符串,下一行可以是图像等,等等。所以imo非常模糊。
  • 将视图模型与不了解单元类型的视图控制器解耦很方便。我用过这个教程:medium.com/flawless-app-stories/…
  • 这里基本上有一个 Any 协议,因此您必须对其进行一些更改才能比较行
  • 如果你符合Equatable 我猜那么你不能定义一个RowViewModel 类型的数组,因为Self 对吗?如果您摆脱协议并转移到 enum 与枚举本身是 Equatable 的相关案例怎么办?
  • @RicoCrescenzio 我只是在考虑那个.. 相关类型将是我的特定类型?

标签: ios swift uitableview generics


【解决方案1】:

正如我在评论中所说,您会得到类似的内容:

class CellViewModel1: Equatable {

    // classes need explicit equatable conformance.
    static func == (lhs: CellViewModel1, rhs: CellViewModel1) -> Bool {
        // your implementation
        return true
    }

}

enum RowViewModel: Equatable { 
    
    // enum automatically is Equatable as long as all cases have Equatable associated types
    case cell1(CellViewModel1)

}

func test() {
    let oldList = [RowViewModel]()
    let newList = [RowViewModel]()

    let deltaAdded = newList.filter { !oldList.contains($0) }.compactMap { newList.firstIndex(of: $0) }
    let deltaRemoved = oldList.filter { !newList.contains($0) }.compactMap { oldList.firstIndex(of: $0) }
}

请注意,枚举和 ViewModel 都必须符合 Equatable。 仍然不能 100% 确定这是否符合您的需求。

【讨论】:

  • 谢谢!我想我可以在枚举本身内部使用 == func,以减少它在周围的传播?
  • @Async- 你不需要枚举中的任何 == 函数,因为 swift 足够聪明,可以为你创建一个,因为所有关联的类型都符合 Equatable。你必须定义一个≠≠ FOR EACH 类,因为我猜每个类都有不同的属性
猜你喜欢
  • 2014-07-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-02-08
  • 2015-08-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多