Swift: Capture inout parameter in closures that escape the called function

后端 未结 2 904
后悔当初
后悔当初 2021-02-10 04:44

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

2条回答
  •  执笔经年
    2021-02-10 05:37

    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)")
                }
        }
    

提交回复
热议问题