// // ThreadSafeDictionary.swift // // Created by Shashank on 29/10/20. // import Foundation import UIKit class ThreadSafeDictionary: Collection { private var dictionary: [V: T] private let concurrentQueue = DispatchQueue(label: "com.nextcloud.ThreadSafeDictionary", attributes: .concurrent) var startIndex: Dictionary.Index { self.concurrentQueue.sync { return self.dictionary.startIndex } } var endIndex: Dictionary.Index { self.concurrentQueue.sync { return self.dictionary.endIndex } } init(dict: [V: T] = [V: T]()) { self.dictionary = dict } func index(after i: Dictionary.Index) -> Dictionary.Index { self.concurrentQueue.sync { return self.dictionary.index(after: i) } } subscript(key: V) -> T? { get { self.concurrentQueue.sync { return self.dictionary[key] } } set(newValue) { self.concurrentQueue.async(flags: .barrier) {[weak self] in self?.dictionary[key] = newValue } } } subscript(index: Dictionary.Index) -> Dictionary.Element { self.concurrentQueue.sync { return self.dictionary[index] } } func removeValue(forKey key: V) { self.concurrentQueue.async(flags: .barrier) {[weak self] in self?.dictionary.removeValue(forKey: key) } } func removeAll() { self.concurrentQueue.async(flags: .barrier) {[weak self] in self?.dictionary.removeAll() } } }