0

Using the below playground, when I print in the async I would assume the counts should be the same, but they are not. It seems that swift does not properly use inout asynchronously, but I need to be able to update an inout reference in an asynchronous call. Any idea how to make this work?

import XCPlayground
import Foundation
XCPlaygroundPage.currentPage.needsIndefiniteExecution = true


class MyObject {

    var name:String!
    var id:Int!

    init(name:String, id:Int){
        self.name = name
        self.id = id
    }

}

struct TempStorage {
    static var baseObjs:[MyObject] = []
}

class myUtils {

    private static func myFunc2(inout myObjs:[MyObject]){

        let priority = DISPATCH_QUEUE_PRIORITY_DEFAULT
        dispatch_async(dispatch_get_global_queue(priority, 0)) {
            let newObj = MyObject(name: "BOB", id: 1)
            myObjs = [newObj]
            print(myObjs.count)
            print(TempStorage.baseObjs.count)
        }


    }

    static func myFunc(inout myObjs:[MyObject]) {
        myUtils.myFunc2(&myObjs)
    }
}

var baseObj = MyObject(name:"SUSY", id:0)
print(TempStorage.baseObjs.count)
myUtils.myFunc(&TempStorage.baseObjs)
steventnorris
  • 5,656
  • 23
  • 93
  • 174
  • Not relevant but you should delete your `var baseObj` as it is unused. – matt Oct 04 '16 at 22:09
  • @matt The accepted answers for the duplicates explain how inout works, but do not offer alternative solutions. Am I to assume there just isn't any solution to updating a reference passed as a parameter asynchronously? – steventnorris Oct 04 '16 at 22:13
  • "updating a reference passed as a parameter asynchronously" The usual pattern is to pass a callback function which the asynchronous code calls when it is finished. – matt Oct 04 '16 at 22:16
  • @matt if you drop that in an answer I'll accept. Seems like that's the only path here since the inout doesn't do a true reference pass. – steventnorris Oct 04 '16 at 22:53
  • But that wouldn't be answering what you asked. What you asked is what is answered by the many duplicates. :) – matt Oct 04 '16 at 23:04

0 Answers0