Search code examples
swiftselfdispatch-queue

Better way of using "self." in background thread?


After adding DispatchQueue.global(qos: .background).async {} to a single function of my code (Xcode 10, Swift 5), the scrollbar looks like this:

enter image description here

These are more than 40 calls to vars and other funcs that need a "self.".

Fixing this isn't hard (Editor > Fix All Issues) but it reduces readability a lot.

I'm aware that it's possible to create new copies of/references to these vars and using them instead of the ones outside but then there'll be a lot of new copies/references.

Is there a third way of fixing this that helps with readability but doesn't change the initial code (too much)?


Solution

  • You can create a nested function or another method to put the code you want to execute in, then pass that nested function or method into DispatchQueue.main.async.

    Here's an example with a nested function:

    Original code:

    class Foo {
        var a = 0
        var b = 0
        var c = 0
    
        func f() {
            a = 1
            b = 1
            c = 1
        }
    }
    

    Doing it asynchronously:

    class Foo {
        var a = 0
        var b = 0
        var c = 0
    
        func f() {
            func doAsync() {
                a = 1
                b = 1
                c = 1
            }
            DispatchQueue.global(qos: .background).async(execute: doAsync)
        }
    }
    

    As you can see, you don't need to add any selfs.