Created
July 17, 2024 10:36
-
-
Save pushpankq/19f9a7e1b78f9dbd65325f644db8953d 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
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