I have established code that makes use of a threadsafe var, to avoid data races.
class ThreadsafeVar<T>
{
private var value = Optional<T>.none
func callAsFunction() -> T?
{
queue.sync(flags: .barrier) { [unowned self] in value }
}
func set(_ value: T?)
{
queue.async(flags: .barrier) { [unowned self] in self.value = value }
}
}
This is called from a "normal" var that is part of a common protocol for a number of different implementations…
private var urls = ThreadsafeVar<[URL]>()
var fileURLs: [URL]
{
get
{
urls()?.sorted(using: .finder, pathComponent: .fullPath) ?? []
}
set { }
}
In this particular example, the setter is not required as the private var is updated as the result of an asynchronous callback from a metadata query - hence the need for concurrency management on the private var.
So, I have created an Actor to replace the "old-fashioned" ThreadsafeVar…
actor UrlManager
{
private var value = [URL]()
func callAsFunction() -> [URL]
{
value
}
func set(_ value: [URL])
{
self.value = value
}
}
I can certainly use await to set the value but I am having problems finding the correct syntax for returning the value from, what would be, the asynchronous call to the actor.
Can anyone help please?