Skip to content

Instantly share code, notes, and snippets.

@pushpankq
Created July 17, 2024 10:36
Show Gist options
  • Save pushpankq/19f9a7e1b78f9dbd65325f644db8953d to your computer and use it in GitHub Desktop.
Save pushpankq/19f9a7e1b78f9dbd65325f644db8953d to your computer and use it in GitHub Desktop.
class ThreadSafeDictionary<Key: Hashable, Value> {
private var dictionary: [Key: Value] = [:]
private let concurrentQueue = DispatchQueue(label: "com.concurrentQueue")
func setValue(_ value: Value, key: Key) {
concurrentQueue.async(flags: .barrier) {
self.dictionary[key] = value
}
}
func value(forKey key: Key) -> Value? {
var result: Value?
concurrentQueue.async(flags: .barrier) {
result = self.dictionary[key]
}
return result
}
func removeValue(forkey key: Key) {
concurrentQueue.async(flags: .barrier) {
self.dictionary.removeValue(forKey: key)
}
}
func removeAll() {
concurrentQueue.async(flags: .barrier) {
self.dictionary.removeAll()
}
}
var allKeys: [Key] {
var keys = [Key]()
concurrentQueue.sync {
keys = Array(self.dictionary.keys)
}
return keys
}
var allValues: [Value] {
var values = [Value]()
concurrentQueue.sync {
values = Array(self.dictionary.values)
}
return values
}
func contains(key: Key) -> Bool {
var result = false
concurrentQueue.sync {
result = self.dictionary.keys.contains(key)
}
return result
}
func print() {
concurrentQueue.sync {
Swift.print(dictionary)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment