Thread-safe Array in Swift

class ThreadSafeArray<T> {    var array = [T]()
let concurrentQueue = DispatchQueue(label: "queue.label", attributes: .concurrent)
// reading array
var first: T? {
var result: T?
self.concurrentQueue.sync {
result = self.array.last
}
return result
}
// updating array
func append(_ newElement: T) {
self.concurrentQueue.async(flags: .barrier) {
self.array.append(newElement)
}
}
}

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
AIWasabi

AIWasabi

Writing tips for iOS programming