Thursday, June 11, 2026
HomeiOS Developmentios - Swift workaround for protocols comparability

ios – Swift workaround for protocols comparability

[ad_1]

I do know evaluating protocols would not make any sense however my state of affairs is dictated by selections and selections taken earlier than me.
A desk view’s information supply is an array of RowViewModel.

protocol RowViewModel {}

there’s nothing in there (but) to make it even conform to Equatable.
Then my desk has totally different cells, all of which implement that protocol:

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

    return rows
}

Cell’s view mannequin:

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

This construction is handy but it surely now shoots me within the again as a result of I now have to calculate delta to ship particular tableView indexes to insert / delete rows. To calculate delta I want RowViewModel to evolve to Equatable, which is feasible however looks like a workaround that defies the preliminary level of utilizing this strategy. I might love to do one thing like this:

let oldList = rows
let newList = getCells()

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

What’s the finest observe right here? Is there a technique to write a comparability perform for concrete sorts conforming to the RowViewModel?

[ad_2]

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments