Appendix C. How Asynchronous Works

Beginners sometimes don’t quite understand what it means for their code to run asynchronously. Asynchronous code runs at an indefinite time. More important, it runs after the surrounding code. This means that the order in which the code appears is not the order in which it will run.

Consider the following (and see Chapter 23):

func doSomeNetworking() {
    // ... prepare url ...
    let session = URLSession.shared 1
    let task = session.downloadTask(with:url) { loc, resp, err in 2
        // ... completion function body goes here ... 4
    }
    task.resume() 3
}

The method downloadTask(with:completionHandler:) calls its completion function asynchronously. It calls it when the networking finishes — and networking takes time. The order in which the chunks of code run is the numerical order of the numbered lines:

1

The code before the call.

2

The call itself.

The code after the call, ...

Get Programming iOS 13 now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.