Created
November 24, 2021 02:00
-
-
Save whoyawn/a2d63d2e0abf1b193fafd9c55b600c8e to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Foundation | |
class ThreadSafeArray<T: Equatable> { | |
private var queue = DispatchQueue(label: "com.threadsafe.array", attributes: .concurrent) | |
private var array: [T] = [] | |
var count: Int { | |
var result = 0 | |
queue.sync { | |
result = array.count | |
} | |
return result | |
} | |
subscript(index: Int) -> T? { | |
get { | |
var result: T? | |
queue.sync { | |
guard self.array.startIndex..<self.array.endIndex ~= index else { return } | |
result = self.array[index] | |
} | |
return result | |
} | |
set { | |
guard let newValue = newValue else { return } | |
queue.async(flags: .barrier) { | |
self.array[index] = newValue | |
} | |
} | |
} | |
var last: T? { | |
var result: T? | |
queue.sync { | |
result = array.last | |
} | |
return result | |
} | |
func append(_ newElement: T) { | |
queue.async(flags: .barrier) { | |
self.array.append(newElement) | |
} | |
} | |
func first(where predicate: (T) throws -> Bool) rethrows -> T? { | |
var result: T? | |
try queue.sync { | |
result = try array.first(where: predicate) | |
} | |
return result | |
} | |
func remove(where predicate: @escaping (T) -> Bool) { | |
queue.async(flags: .barrier) { | |
guard let index = self.array.firstIndex(where: predicate) else { return } | |
self.array.remove(at: index) | |
} | |
} | |
func contains(_ element: T) -> Bool { | |
var result = false | |
queue.sync { | |
result = array.contains(element) | |
} | |
return result | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment