Created
July 31, 2023 05:59
-
-
Save zhigang1992/c2a446cea4c51b3b4d21a0313296fbeb to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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