Swift async/await

Note: I’m going through draft posts that go back to 2014 and publishing where they still may have value. They may not be 100% upto date but better published late than never.

Swift comes with async/await syntax/functionality, however the support is dependent upon version of Swift and more importantly whether it’s the Mac (I’ll include iOS and watch OS in this) version of the Linux version.

Currently I’m playing with Swift on Linux and using the URLSession.shared.dataTask which is essentially a callback function. The URLSession.shared.data async/await version currently does not exist on Linux. So let’s create our own version and look at the process and ofcourse, how to use async/await (if you’ve used C#, TypeScript with async/await you’ll already know the basics of using the syntax).

Functions should be declared as async, so for example

func data(for request: URLRequest) async -> (Data, URLResponse) {
  // do something
}

Here’s an example of using the URLSession.shared.dataTask and declaring the code in an async method

#if canImport(FoundationNetworking)
public extension URLSession {
    func data(for request: URLRequest) async -> (Data, URLResponse) {
        await withCheckedContinuation { continuation in
            URLSession.shared.dataTask(with: request) { data, response, error in
                continuation.resume(returning: (data!, response!))
            }.resume()
        }
    }
}
#endif

Now, in usage, we can do this

let data = await URLSession.shared.data(for: request)