Inout parameter in async callback does not work as expected

前端 未结 4 1697
有刺的猬
有刺的猬 2020-11-29 12:26

I\'m trying to insert functions with inout parameter to append data received from async callback to an outside array. However, it does not work. And I tried eve

4条回答
  •  情书的邮戳
    2020-11-29 13:12

    I had a similar goal and ran into the same issue where results inside the closure were not being assigned to my global inout variables. @rintaro did a great job of explaining why this is the case in a previous answer.

    I am going to include here a generalized example of how I worked around this. In my case I had several global arrays that I wanted to assign to within a closure, and then do something each time (without duplicating a bunch of code).

    // global arrays that we want to assign to asynchronously
    var array1 = [String]()
    var array2 = [String]()
    var array3 = [String]()
    
    // kick everything off
    loadAsyncContent()
    
    func loadAsyncContent() {
    
        // function to handle the query result strings
        // note that outputArray is an inout parameter that will be a reference to one of our global arrays
        func resultsCallbackHandler(results: [String], inout outputArray: [String]) {
    
            // assign the results to the specified array
            outputArray = results
    
            // trigger some action every time a query returns it's strings
            reloadMyView() 
        }
    
        // kick off each query by telling it which database table to query and
        // we're also giving each call a function to run along with a reference to which array the results should be assigned to
        queryTable("Table1") {(results: [String]) -> Void in resultsCallbackHandler(results, outputArray: &self.array1)}
        queryTable("Table2") {(results: [String]) -> Void in resultsCallbackHandler(results, outputArray: &self.array2)}
        queryTable("Table3") {(results: [String]) -> Void in resultsCallbackHandler(results, outputArray: &self.array3)}
    }
    
    func queryTable(tableName: String, callback: (foundStrings: [String]) -> Void) {
    
        let query = Query(tableName: tableName)
        query.findStringsInBackground({ (results: [String]) -> Void in
    
            callback(results: results)
        })
    }
    
    // this will get called each time one of the global arrays have been updated with new results
    func reloadMyView() {
    
        // do something with array1, array2, array3
    }
    

提交回复
热议问题