我知道比較協議沒有任何意義,但我的情況取決于我之前做出的選擇和決定。表視圖的資料源是一個 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
...
}
這種結構很方便,但它現在讓我背道而馳,因為我現在需要計算增量以發送特定的 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 的具體型別撰寫比較函式?
uj5u.com熱心網友回復:
正如我在評論中所說,你會有類似的東西:
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) }
}
請注意, enum 和 ViewModel 都必須符合Equatable. 仍然不能 100% 確定這是否適合您的需要。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/362385.html
上一篇:Swift委托模式:委托=Nil
下一篇:由于通用鏈接存盤拒絕
