Search code examples
swiftmultithreadingparameterspass-by-referenceswift-playground

Modifying reference type parameters in Swift; are changes immediately visible outside?


I have a Swift playground that contains several classes in the source folder. These classes have tick() functions that are called as fast as possible with a while true { }. I am using a parallel thread to do this, to stop Xcode from locking up, with this code:

DispatchQueue.global(qos: .background).async {
    BackgroundThread.startMainLoop(scene: scene)
}

// other file
public struct BackgroundThread {
    public static func startMainLoop (scene: SKScene) {
        let songController = SongController()
        let uiManager = UIManager(scene: scene)

// The UIManager is going to modify this scene.
// Will the changes be available to BackgroundThread and/or the main file?

        while true {
            songController.tick()
            uiManager.tick()
        }
    }
}

Because the main playground script is very slow, I have moved the repeating loop to a compiled class in the Sources folder.

I am passing an SKScene object to a UIManager compiled class, which I will need to update the UI in this (relatively complicated) scene faster than the main playground script can manage.

The main playground script calls a startMainLoop() function in the parallel thread. It passes in the SKScene object. This function never returns, since it contains a never-ending loop. Is there a way I can modify the passed object in a manner that modifies the scene displayed on the screen, live, without the function ever having to return (which means that inout is not an option), assuming this does not happen by default?


Solution

  • Reference type means the value is a reference -- i.e. a pointer to an object. When you pass or assign a reference, you get a copy of the reference (it is pass-by-value without inout), but multiple copies of the reference point to the same object, and modifications to the object through any reference that points to it is visible through any other reference that points to it.