TEAM LICENSES: Save money and learn new skills through a Hacking with Swift+ team license >>

Concurrency in top-level code

Available from Swift 5.7

Paul Hudson      @twostraws

SE-0343 upgrades Swift’s support for top-level code – think main.swift in a macOS Command Line Tool project – so that it supports concurrency out of the box. This is one of those changes that might seem trivial on the surface, but took a lot of work to make happen.

In practice, it means you can write code like this directly into your main.swift files:

import Foundation
let url = URL(string: "https://hws.dev/readings.json")!
let (data, _) = try await URLSession.shared.data(from: url)
let readings = try JSONDecoder().decode([Double].self, from: data)
print("Found \(readings.count) temperature readings")

Previously, we had to create a new @main struct that had an asynchronous main() method, so this new, simpler approach is a big improvement.

Hacking with Swift is sponsored by String Catalog.

SPONSORED Get accurate app localizations in minutes using AI. Choose your languages & receive translations for 40+ markets!

Localize My App

Sponsor Hacking with Swift and reach the world's largest Swift community!

Other changes in Swift 5.7…

Download all Swift 5.7 changes as a playground Link to Swift 5.7 changes

Browse changes in all Swift versions

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.