SynchronizedDictionary.swift 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. //
  2. // SynchronizedDictionary.swift
  3. // TLPhotoPicker
  4. //
  5. // Created by wade.hawk on 30/03/2019.
  6. //
  7. import Foundation
  8. public class SynchronizedDictionary<K:Hashable,V> {
  9. private var dictionary: [K:V] = [:]
  10. private let accessQueue = DispatchQueue(label: "SynchronizedDictionaryAccess",
  11. attributes: .concurrent)
  12. deinit {
  13. //print("deinit SynchronizedDictionary")
  14. }
  15. public func removeAll() {
  16. self.accessQueue.async(flags:.barrier) {
  17. self.dictionary.removeAll()
  18. }
  19. }
  20. public func removeValue(forKey: K) {
  21. self.accessQueue.async(flags:.barrier) {
  22. self.dictionary.removeValue(forKey: forKey)
  23. }
  24. }
  25. public func forEach(_ closure: ((K,V) -> Void)) {
  26. self.accessQueue.sync {
  27. self.dictionary.forEach{ arg in
  28. let (key, value) = arg
  29. closure(key,value)
  30. }
  31. }
  32. }
  33. public subscript(key: K) -> V? {
  34. set {
  35. self.accessQueue.async(flags:.barrier) {
  36. self.dictionary[key] = newValue
  37. }
  38. }
  39. get {
  40. var element: V?
  41. self.accessQueue.sync {
  42. element = self.dictionary[key]
  43. }
  44. return element
  45. }
  46. }
  47. }