Set, OrderedSet, SetAlgebra, and SwiftUI

Where are these equatable expectations stated / documented?


Two ideas IRT how to do OrderedSet based selection:

  1. start with having a way to construct a new ordered set from existing:
extension OrderedSet {
    mutating func change(to newValue: Set<Element>) {
        for old in self {
            if !newValue.contains(old) {
                remove(old)
            }
        }
        for new in newValue {
            if !contains(new) {
                append(new)
            }
        }
    }
}

this will not effect the order of existing items, items no longer in the set will be removed and new items will be added to the end.

Then, as SwiftUI wants "Set" give it a set made out of orderedSet:

    private var cachedSet: Set<ID>!
    
    var orderedSet: OrderedSet<ID> = [] {
        didSet { cachedSet = nil }
    }
    
    var selection: Set<ID> {
        get {
            if cachedSet == nil {
                cachedSet = Set(orderedSet)
            }
            return cachedSet
        }
        set {
            orderedSet.change(to: newValue)
            cachedSet = newValue
        }
    }

Make sure that "cachedSet" value is getting cleared if you change orderedSet.
This should satisfy SwiftUI and hopefully the price of converting from OrderedSet to Set after cached value invalidation will not be too high.

  1. Ignore SwiftUI's "selection" and implement selection logic yourself (in which case you could use anything including OrderedSet. It's not hard at all.
1 Like