Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
struct TreadSafeDict<Key:Hashable, Element> {
let queue = DispatchQueue(label: "thread-safe-queue")
typealias DictionaryType = [Key : Element]
private var _elements = DictionaryType()
init(elements: DictionaryType) {
queue.sync {
self._elements = elements
}
}
mutating func atomically(_ transform: (inout DictionaryType) -> ()) {
queue.sync {
transform(&self._elements)
}
}
}
extension TreadSafeDict: Collection {
var startIndex: Index { return _elements.startIndex }
var endIndex: Index { return _elements.endIndex }
subscript(index: Index) -> DictionaryType.Iterator.Element {
get { return self._elements[index] }
}
subscript(key: Key) -> Element? {
get{
queue.sync { return _elements[key] }
}
set{
queue.sync {
_elements[key] = newValue
}
}
}
typealias Index = DictionaryType.Index
typealias Element = DictionaryType.Element
func index(after i: TreadSafeDict.DictionaryType.Index) -> TreadSafeDict.DictionaryType.Index {
return _elements.index(after: i)
}
}
extension TreadSafeDict: ExpressibleByDictionaryLiteral {
typealias Key = Key
typealias Value = Element
init(dictionaryLiteral elements: (Key, Element)...) {
self.atomically { (internalElements) in
for (key,value) in elements{
internalElements[key] = value
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.