diff --git a/Sources/SpellbookFoundation/ValueObserving/ValueStore.swift b/Sources/SpellbookFoundation/ValueObserving/ValueStore.swift index 3dabe05..e85727c 100644 --- a/Sources/SpellbookFoundation/ValueObserving/ValueStore.swift +++ b/Sources/SpellbookFoundation/ValueObserving/ValueStore.swift @@ -61,8 +61,9 @@ public final class ValueStore: ValueObserving { valueLock.withLock { currentValueGet[updateDepth > 0 ? updateDepth - 1 : 0] } } - public func update(_ value: Value, context: Any? = nil) { - update(context: context) { $0 = value } + @discardableResult + public func update(_ value: Value, context: Any? = nil) -> Value { + update(context: context) { updateSwap(&$0, value) } } public func update( @@ -222,3 +223,81 @@ extension ValueStore { .init { self.value } } } + +extension ValueStore { + public convenience init() where Value: ExpressibleByArrayLiteral { + self.init(initialValue: []) + } + + public func append(_ element: Value.Element) where Value: RangeReplaceableCollection { + update { $0.append(element) } + } + + public func removeAll(where shouldBeRemoved: (Value.Element) -> Bool) where Value: RangeReplaceableCollection { + update { $0.removeAll(where: shouldBeRemoved) } + } +} + +extension ValueStore { + public convenience init() where Value == Set { + self.init(initialValue: []) + } + + @discardableResult + public func insert( + _ element: Element + ) -> (inserted: Bool, memberAfterInsert: Element) where Value == Set { + update { $0.insert(element) } + } + + @discardableResult + public func remove(_ element: Element) -> Element? where Value == Set { + update { $0.remove(element) } + } + + public func popFirst() -> Element? where Value == Set { + update { $0.popFirst() } + } + + public func formUnion( + _ other: S + ) where Value == Set, S: Sequence, Element == S.Element { + update { $0.formUnion(other) } + } + + public func subtract( + _ other: S + ) where Value == Set, S: Sequence, Element == S.Element { + update { $0.subtract(other) } + } + + public func formIntersection( + _ other: S + ) where Value == Set, S: Sequence, Element == S.Element { + update { $0.formIntersection(other) } + } + + public func formSymmetricDifference( + _ other: S + ) where Value == Set, S: Sequence, Element == S.Element { + update { $0.formSymmetricDifference(other) } + } +} + +extension ValueStore { + public func popFirst() -> Value.Element? where Value == [Key: Element] { + update { $0.popFirst() } + } + + @discardableResult + public func updateValue( + _ value: Element, forKey key: Key + ) -> Element? where Value == [Key: Element] { + update { $0.updateValue(value, forKey: key) } + } + + @discardableResult + public func removeValue(forKey key: Key) -> Element? where Value == [Key: Element] { + update { $0.removeValue(forKey: key) } + } +}