Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import Foundation
- protocol Identifiable {
- associatedtype Identifier: Hashable
- var identifier: Identifier { get }
- }
- protocol Updatable {
- associatedtype Source: Identifiable
- // implement this to update this type from a source representation
- func update(from source: Source)
- // implement this to perform any cleanup before removing this element
- func willBeDeleted()
- }
- protocol CollectionDiffable {
- associatedtype Element: Updatable
- var elementMap: [Element.Source.Identifier: Element] { get }
- func update(source: [Element.Source])
- // implement this to create a new Element from a Source
- func add(source: Element.Source)
- // implement this to remove an Element from the collection
- func remove(identifier: Element.Source.Identifier)
- }
- extension CollectionDiffable {
- func update(sources: [Element.Source]) {
- let identifiers = sources.map { $0.identifier }
- elementMap.keys
- .filter { !identifiers.contains($0) }
- .forEach {
- if let itemToDelete = elementMap[$0] {
- itemToDelete.willBeDeleted()
- }
- self.remove(identifier: $0)
- }
- sources.forEach { source in
- let identifier = source.identifier
- if let existingUpdatable = elementMap[identifier] {
- existingUpdatable.update(from: source)
- } else {
- self.add(source: source)
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement