Skip to content

Instantly share code, notes, and snippets.

@zhigang1992
Created July 31, 2023 05:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zhigang1992/c2a446cea4c51b3b4d21a0313296fbeb to your computer and use it in GitHub Desktop.
Save zhigang1992/c2a446cea4c51b3b4d21a0313296fbeb to your computer and use it in GitHub Desktop.
import Observation
@Observable
final class ObservableDictionary<Key: Hashable, Value> {
@ObservationIgnored fileprivate var backingDictionary: Dictionary<Key, Value> = [:]
public subscript(key: Key) -> Value? {
get {
let keyPath = \ObservableDictionary<Key, Value>.backingDictionary[key]
access(keyPath: keyPath)
return backingDictionary[key]
}
set {
let keyPath = \ObservableDictionary<Key, Value>.backingDictionary[key]
withMutation(keyPath: keyPath) {
backingDictionary[key] = newValue
}
}
}
}
extension ObservableDictionary: ExpressibleByDictionaryLiteral {
convenience init(dictionaryLiteral elements: (Key, Value)...) {
self.init()
self.backingDictionary = Dictionary(uniqueKeysWithValues: elements)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment