I tried to write an \"editor\" class that could retain a reference to a property on a different object for later mutation. I first wrote the editor class to receive a closure f
It can be done as follows. )Notice that the closure and the inout param have the same lifespan.)
/// A class providing access to a resource with an inout parameter in an escaping closure.
class ProtectedResource {
private var protectedResourceArray = [ValueType]()
private var protectedResourceArrayLock = NSRecursiveLock()
private let opq = OperationQueue()
func performWithResource(block: @escaping (inout [ValueType]) -> ()) {
opq.addOperation { [weak self] in
guard let strongSelf = self else {
return
}
strongSelf.protectedResourceArrayLock.lock()
block(&strongSelf.protectedResourceArray)
strongSelf.protectedResourceArrayLock.unlock()
}
}
}
/// Some other class using that in out parameter.
func run() {
func updateArray(array: inout [String]) {
print("Performing on \(array)")
array.append("test")
}
protectedResource.performWithResource(block: updateArray)
protectedResource.performWithResource {
print("Performing on \($0)")
}
}