-
Notifications
You must be signed in to change notification settings - Fork 8
/
ThreadSafeDictionary.swift
56 lines (48 loc) · 1.52 KB
/
ThreadSafeDictionary.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
//
// ThreadSafeDictionary.swift
//
// Created by Shashank on 29/10/20.
//
class ThreadSafeDictionary<T>: Collection {
private var dictionary: [String: T]
private let concurrentQueue = DispatchQueue(label: "Dictionary Barrier Queue",
attributes: .concurrent)
var startIndex: Dictionary<String, T>.Index {
return self.dictionary.startIndex
}
var endIndex: Dictionary<String, T>.Index {
return self.dictionary.endIndex
}
init(dict: [String: T] = [String: T]()) {
self.dictionary = dict
}
// this is because it is an apple protocol method
// swiftlint:disable identifier_name
func index(after i: Dictionary<String, T>.Index) -> Dictionary<String, T>.Index {
return self.dictionary.index(after: i)
}
// swiftlint:enable identifier_name
subscript(key: String) -> T? {
set(newValue) {
self.concurrentQueue.async(flags: .barrier) {[weak self] in
self?.dictionary[key] = newValue
}
}
get {
self.concurrentQueue.sync {
return self.dictionary[key]
}
}
}
// has implicity get
subscript(index: Dictionary<String, T>.Index) -> Dictionary<String, T>.Element {
self.concurrentQueue.sync {
return self.dictionary[index]
}
}
func removeAll() {
self.concurrentQueue.async(flags: .barrier) {[weak self] in
self?.dictionary.removeAll()
}
}
}