ThreadSafeDictionary.swift 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. //
  2. // ThreadSafeDictionary.swift
  3. //
  4. // Created by Shashank on 29/10/20.
  5. //
  6. class ThreadSafeDictionary<V: Hashable, T>: Collection {
  7. private var dictionary: [V: T]
  8. private let concurrentQueue = DispatchQueue(label: "Dictionary Barrier Queue", attributes: .concurrent)
  9. var startIndex: Dictionary<V, T>.Index {
  10. self.concurrentQueue.sync {
  11. return self.dictionary.startIndex
  12. }
  13. }
  14. var endIndex: Dictionary<V, T>.Index {
  15. self.concurrentQueue.sync {
  16. return self.dictionary.endIndex
  17. }
  18. }
  19. init(dict: [V: T] = [V: T]()) {
  20. self.dictionary = dict
  21. }
  22. func index(after i: Dictionary<V, T>.Index) -> Dictionary<V, T>.Index {
  23. self.concurrentQueue.sync {
  24. return self.dictionary.index(after: i)
  25. }
  26. }
  27. subscript(key: V) -> T? {
  28. get {
  29. self.concurrentQueue.sync {
  30. return self.dictionary[key]
  31. }
  32. }
  33. set(newValue) {
  34. self.concurrentQueue.async(flags: .barrier) {[weak self] in
  35. self?.dictionary[key] = newValue
  36. }
  37. }
  38. }
  39. subscript(index: Dictionary<V, T>.Index) -> Dictionary<V, T>.Element {
  40. self.concurrentQueue.sync {
  41. return self.dictionary[index]
  42. }
  43. }
  44. func removeValue(forKey key: V) {
  45. self.concurrentQueue.async(flags: .barrier) {[weak self] in
  46. self?.dictionary.removeValue(forKey: key)
  47. }
  48. }
  49. func removeAll() {
  50. self.concurrentQueue.async(flags: .barrier) {[weak self] in
  51. self?.dictionary.removeAll()
  52. }
  53. }
  54. }