ThreadSafeDictionary.swift 1.6 KB

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