Swift Concurrency’s TaskGroup explained

With Apple's overhaul of how concurrency will work in Swift 5.5 and newer, we need to learn a lot of things from scratch. While we might have used DispatchQueue.async or other mechanisms to kick off multiple asynchronous tasks in the past, we shouldn't use these older concurrency tools in Swift's new concurrency model.

Luckily, Swift Concurrency comes with many features already which means that for a lot of our old uses cases, a new paradigm exists.

In this post, you will learn what Swift Concurrency's task groups are, and how you can use them to concurrently perform a lot of work.

Which problem does TaskGroup solve?

Before I show you how you can use a task group, I'd like to explain when a task group is most likely the correct tool for your job. Or rather, I'd like to explain the problem that task groups were designed to solve.

Consider the following example.

Let's say that you fetched a list of ids from your server. These ids represent the ids of movies that your user has marked as a favorite. By returning ids instead of full-blown movie objects, your user can save a lot of data, assuming that clients can (and will) cache movie objects locally. This allows you to either look up a movie in your local cache, or to fetch the movie from the server if needed.

The code to fetch these movie ids might look a bit like this:

func getFavoriteIds(for user: User) async -> [UUID] {
    return await network.fetchUserFavorites(for: user)
}

func fetchFavorites(user: User) async -> [Movie] {
    // fetch Ids for favorites from a remote source
    let ids = await getFavoriteIds(for: user)

    // perform work to obtain `[Movie]`
}

So far so good. If you're somewhat familiar with Swift Concurrency's async/await concept this code shouldn't look too scary.

Now that we have an array of UUID, we need to somehow convert this array to Movie objects. In this case, I don't care about the order of the ids and the resulting movies matching. And I don't want to fetch movies one by one because that might take a while.

I'd like to fetch as many movies at the same time as I possibly can.

This sentence above is essentially the key to knowing when we should use a task group.

In this case, I want to run a variable number of tasks concurrently, and every task produces the same type of output. This use case is exactly what task groups are good at. They allow you to spawn as many tasks as you want, and all of these tasks will run concurrently. One constraint is that every task must produce the same output. In this case, that's not a problem. We want to convert from UUID to Movie every time, which means that our task will always produce the same output.

Let's take a look at an example.

Using a TaskGroup in your code

Task groups can either be throwing or non-throwing. This might sound obvious, but the (non-)throwing nature of your task group has to be defined when you create it. In this case, I'm going to use a non-throwing task group. Let's see how a task group can be created.

Defining a task group

A task group can be created as follows:

await withTaskGroup(of: Movie.self) { group in

}

The withTaskGroup function is a global function in Swift that takes two arguments. The first argument specifies the type of result that your tasks produce. If your tasks don't have any output, you would write Void.self here since that would be the return type for each individual task. In this case, it's Movie.self because all tasks will produce a Movie instance.

Note that in Xcode 26 it's not mandatory to specify the return type of your child tasks. The compiler can infer the return type through the very first task that you add to your group. Note that all your tasks must produce the same output. If you want to have tasks that produce varying output, you can leverage enums to do so. I explain how to do this in my post on building a variadic task group.

If the tasks in a task group can throw errors, you should use withThrowingTaskGroup instead of withTaskGroup.

The second argument is a closure in which we'll schedule and handle all of our tasks. This closure receives an instance of TaskGroup<Output> as its only argument. The Output generic will correspond with your task output. So in this case the actual type would be TaskGroup<Movie>.

The withTaskGroup function is marked async which means that need to await its result. In this case, we don't return anything from the closure that we pass to withTaskGroup. If we did return something, the returned object would be the return value for the call to withTaskGroup and we could assign this output to a property or return it from a function.

In this case, we'll want to return something from fetchFavorites. Here's what that looks like:

func fetchFavorites(user: User) async -> [Movie] {
    // fetch Ids for favorites from a remote source
    let ids = await getFavoriteIds(for: user)

    // load all movies concurrently
    return await withTaskGroup(of: Movie.self) { group in
        var movies = [Movie]()

        // obtain movies

        return movies
    }
}

While this code compiles just fine, it's not very useful. Let's add some tasks to our task group so we can fetch movies.

Adding tasks to a TaskGroup

The TaskGroup object that is passed to our closure is used to schedule tasks in the group, and also to obtain the results of these tasks if needed. Let's see how we can add tasks to the group first, and after that I'll show you how you can obtain the results of your tasks by iterating over the group's results.

To load movies, we'll call the following async function from a new task. This function would be defined alongside fetchFavorites and getFavoriteIds:

func getMovie(withId id: UUID) async -> Movie {
    return await network.fetchMovie(withId: id)
}

To call this function from within a new task in the task group, we need to call addTask on the TaskGroup as follows:

func fetchFavorites(user: User) async -> [Movie] {
    // fetch Ids for favorites from a remote source
    let ids = await getFavoriteIds(for: user)

    // load all movies concurrently
    return await withTaskGroup(of: Movie.self) { group in
        var movies = [Movie]()

        // adding tasks to the group and fetching movies
        for id in ids {
            group.addTask {
                return await self.getMovie(withId: id)
            }
        }

        return movies
    }
}

I added a for loop to the task group closure to iterate over the ids that were fetched. For every fetched id I call group.addTask and pass it a closure that contains my task. This closure is async which means that we can await the result of some function call. In this case I want to await and return the result of self.getMovie. Note that I don't need to capture self weakly in the closure I pass to addTask. The reason for this is that the task I created can never outlive the scope it's defined in (more on that later), this means that no retain cycles are created here. The Swift compiler guarantees that our tasks don't outlive the scope they're defined in so we can be absolutely sure that our tasks don't create retain cycles.

Every task that's added to the task group with group.addTask must return a Movie instance because that's the task output type that we passed to withTaskGroup. As soon as a task is added to the task group it will beginning running concurrently with any other tasks that I may have already added to the group.

Collecting your task group's results

You might notice that while I add a bunch of tasks to the group, I never actually await or return the output of my tasks. To do this, we need to iterate asynchronously over the task group and obtain the results of its tasks. The TaskGroup object conforms to AsyncSequence which means that we can iterate over it using for await as follows:

func fetchFavorites(user: User) async -> [Movie] {
    // fetch Ids for favorites from a remote source
    let ids = await getFavoriteIds(for: user)

    // load all favorites concurrently
    return await withTaskGroup(of: Movie.self) { group in
        var movies = [Movie]()
        movies.reserveCapacity(ids.count)

        // adding tasks to the group and fetching movies
        for id in ids {
            group.addTask {
                return await self.getMovie(withId: id)
            }
        }

        // grab movies as their tasks complete, and append them to the `movies` array
        for await movie in group {
            movies.append(movie)
        }

        return movies
    }
}

By using for await movie in group the task group will provide us with movies as soon as they are obtained. Note that the results will be gathered in completion order. In other words, whichever movie is fully fetched first, will be returned first. The order in which we added tasks to the group does not necessarily matter. Although for very small/quick tasks it may happen that completion order can be the same as the order in which we added the tasks but this is never guaranteed. This is why I mentioned I didn't care about ordering earlier.

Whenever a task completes, the group provides us with the task output, and we can append this output to the movies array. Once all tasks are completed and we have appended all output to the movies array, we return this array from our task group closure.

This means that we can return the result of awaiting withTaskGroup from fetchFavorites since the output is an array of movies.

Note that we don't return from the closure that's provided to withTaskGroup until all tasks have completed due to the asynchronous for loop. This loop doesn't complete until all tasks in the group complete, and all output has been provided to us. Of course, we could exit our loop early with a break just like you can in a normal loop.

The example you've seen so far follows a pretty happy path. Let's consider two additional situations, in which we'll have to deal with errors thrown by the tasks that were added to the group:

  1. One of the tasks throws an error
  2. The task group is cancelled

TaskGroups and throwing tasks

I already mentioned that a task group for tasks that can throw should be created with withThrowingTaskGroup. We'd need to do this if the getMovie function you saw earlier could throw an error. If it could, it would look like this:

func getMovie(withId id: UUID) async throws -> Movie {
    return try await network.fetchMovie(withId: id)
}

The code to fetch a user's favorite movies would in turn be updated as follows:

func fetchFavorites(user: User) async throws -> [Movie] {
    // fetch ids for favorites from a remote source
    let ids = await getFavoriteIds(for: user)

    // load all favorites concurrently
    return try await withThrowingTaskGroup(of: Movie.self) { group in
        var movies = [Movie]()
        movies.reserveCapacity(ids.count)

        // adding tasks to the group and fetching movies
        for id in ids {
            group.addTask {
                return try await self.getMovie(withId: id)
            }
        }

        // grab movies as their tasks complete, and append them to the `movies` array
        for try await movie in group {
            movies.append(movie)
        }

        return movies
    }
}

The changes we needed to make to handle throwing tasks are relatively small. All I had to do was to add try where appropriate, and use withThrowingTaskGroup instead of withTaskGroup. However, there's a huge difference here in terms of what might happen.

In this example, I'm fetching movies by calling try await self.getMovie(withId: id). This means that the getMovie operation might throw an error. When it does, it's not a big deal per se. A task can fail without impacting any of the other tasks in the task group. This means that failing to load one of the movie does not necessarily impact the other tasks in my task group. However, because I iterate over the fetched movies using for try await movie in group, a single failure does impact other tasks in my group.

As we iterate over the group's results, a failed task also counts as a result. However, when the group's next() function is called internally to obtain the next result, it will throw the error that was thrown by the failing task so we can inspect and handle it if needed. In a for loop, I can only write try await which means that when the group throws an error from its next() function, this error is thrown out from the withThrowingTaskGroup closure since we don't handle (or ignore) it.

When an error is thrown from the closure provided to withThrowingTaskGroup, the task group will fail with that error. Before this error is thrown, the task group will mark any unfinished tasks as cancelled to allow them to stop executing work as soon as possible in order to comply with Swift Concurrency's cooperative cancellation. Once all tasks have completed (either by finishing their work or throwing an error), the task group will throw its error and complete.

In the example we're working with here, we can prevent a single failure from cancelling all in progress work. The solution would be to make sure the closure I pass to addTask doesn't throw. I could handle the errors thrown by getMovie and return some kind of default movie which probably isn't the best solution, or I could return nil. If returning nil is reasonable for your use case, you could also write try? await self.getMovie(withId: id) to ignore the error and return nil instead of handling the error in a do {} catch {} block.

Depending on how the tasks you add to your task group were written, cancelling one of your tasks might have a similar effect. In Swift Concurrency, it's perfectly acceptable to throw an error from a task when it's cancelled. This means that if your task throws a cancellation error, it could propagate through your task group in the exact same way that other thrown errors propagate through your task group if it ends up being thrown out of your withThrowingTaskGroup closure.

The bottom line here is that individual tasks throwing errors do not impact the task group and its enclosing task per se. It's only when this error ends up being thrown from your withThrowingTaskGroup closure that all unfinished tasks get cancelled, and the original error is thrown from the task group's task once all child tasks have finished. All this talk about errors and completing the task group's task segues nicely into the last topic I want to cover; the lifecycle of your task group's tasks.

Understanding the lifecycle of tasks in a TaskGroup

When you add tasks in a task group, you enter into a very important (explicit) contract. Swift's concurrency mechanisms are structured (pun intended) around the concept of Structured Concurrency. Async lets as well as task group child tasks both adhere to this idea.

The core idea behind structured concurrency is that a task cannot outlive the scope of its parent task. And similarily, no TaskGroup child task may outlive the scope of the withTaskGroup closure. This is achieved by implicitly awaiting on all tasks to complete before returning from the closure you pass to withTaskGroup.

When you know that tasks in a group cannot outlive the group they belong to, the error throwing / cancellation strategy I outlined above makes a lot of sense.

Once the task that manages the group throws an error, the scope of the task group has completed. If we still have running tasks at that time, the tasks would outlive their group which isn't allowed. For that reason, the task group will first wait for all of its tasks to either complete or throw a cancellation error before throwing its own error and exitting its scope.

When thinking of the code you've seen in this post, I've awaited the results of all child tasks explicitly by iterating over the group. This means that by the time we hit return movies all tasks are done already and no extra waiting is needed.

However, we don't have to await the output of our tasks in all cases. Let's say we have a bunch of tasks that don't return anything. We'd only write the following:

print("Before task group")
await withTaskGroup(of: Void.self) { group in
    for item in list {
        group.addTask {
            await doSomething()
            print("Task completed")
        }
    }
    print("For loop completed")
}
print("After task group")

Like I explained earlier, the task group's child tasks are always implicitly awaited before exitting the closure in which they were created in order to comply with the requirements of structured concurrency. This means that even if we don't await the result of our tasks, the tasks are guaranteed to be completed when we exit the withTaskGroup closure.

I've added some prints to the code snippet before to help you see this principle in action. When I run the code above, the output would look a bit like this:

print("Before task group")
print("For loop completed")
print("Task completed")
print("Task completed")
print("Task completed")
print("After task group")

The reason for that is the implicit awaiting of tasks in a group I just mentioned. The task group is not allowed to complete before all of the tasks it manages have also completed.

In Summary

In this post you learned a lot. You learned that tasks groups are a tool to concurrently perform an arbitrary number of tasks that produce the same output. I showed you how you can write a basic task group to concurrently fetch an arbitrary number of movies based on their ids as an example. You learned that task groups will run as many tasks at once as possible, and that you can obtain the results of these tasks using an async for loop.

After that, I explained how errors and cancellation work within a task group. You learned that whenever a task throws an error you can either handle or ignore this error. You also saw that if you throw an error from your task group closure, this will cause all unfinished tasks in the group to be marked as cancelled, and you learned that the original error will be thrown from task group once all tasks have completed.

Lastly, I explained how tasks within a task group cannot outlive the task group due to the guarantees made by Swift Concurrency, and that a task group will implicitly await all of its child tasks before completing to make sure none of its tasks are still running by the time the task group completes.

Huge thanks to Konrad for reviewing this post and providing some important corrections surrounding errors and cancellation.

Expand your learning with my books

Practical Combine header image

Learn everything you need to know about Combine and how you can use it in your projects with Practical Combine. It contains:

  • Thirteen chapters worth of content.
  • Playgrounds and sample projects that use the code shown in the chapters.
  • Free updates for future iOS versions.

The book is available as a digital download for just $39.99!

Learn more

Using UISheetPresentationController in SwiftUI 3

This post applies to the version of SwiftUI that shipped with iOS 15, also known as Swift 3. To learn how you can present a bottom sheet on iOS 16 and newer, take a look at this post.

With iOS 15, Apple introduced the ability to easily implement a bottom sheet with UISheetPresentationController in UIKit. Unfortunately, Apple didn't extend this functionality to SwiftUI just yet (I'm hoping one of the iOS 15 betas adds this...) but luckily we can make use of UIHostingController and UIViewRepresentable to work around this limitation and use a bottom sheet on SwiftUI.

In this post, I will show you a very simple implementation that might not have everything you need. After I tweeted about this hacky little workaround, someone suggested this very nice GitHub repository from Adam Foot that works roughly the same but with a much nicer interface. This post's goal is not to show you the best possible implementation of this idea, the repository I linked does a good job of that. Instead, I'd like to explain the underlying ideas and principles that make this work.

The underlying idea

When I realized it wasn't possible to present a bottom sheet in SwiftUI with the new UISheetPresentationController I started wondering if there was some way around this. I know that there are some issues with presenting a CloudKit sharing controller from SwiftUI as well, and a popular workaround is to have a UIButton in your view that presents the sharing controller.

While not strictly needed to make the bottom sheet work (as shown by the repository linked in the intro), I figured I would follow a similar pattern. That way I would be able to create a UIViewController and present it on top of the view that the button is presented in. The nice thing about that over how Adam Foot implemented his bottom sheet is that we can use the button's window to present the popover. Doing this will ensure that our view is always presented in the correct window if your app supports multiple windows. The cost is that, unfortunately, our API will not feel very at home in SwiftUI.

I figured that's ok for this writeup. If you want to see an implementation with a nicer API, look at what Adam Foot did in his implementation. The purpose of this post is mostly to explain how and why this works rather than providing you with the absolute best drop-in version of a bottom sheet for SwiftUI.

Implementing the BottomSheetPresenter

As I mentioned, a useful method to present a UICloudSharingController in SwiftUI is to present a UIButton that will in turn present the sharing controller. The reason this is needed is because, for some reason, presenting the sharing controller directly does not work. I don't fully understand why, but that's way beyond the scope of this post (and maybe a good topic for another post once I figure it out).

We'll follow this pattern for the proof of concept we're building in this post because it'll allow me to present the bottom sheet on the current window rather than any window. The components involved will be a BottomSheetPresenter which is a UIViewRepresentable that shows my button, and a BottomSheetWrapperController that puts a SwiftUI view in a view controller that I'll present.

Let's implement the presenter first. I'll use the following skeleton:

struct BottomSheetPresenter<Content>: UIViewRepresentable where Content: View{
    let label: String
    let content: Content
    let detents: [UISheetPresentationController.Detent]

    init(_ label: String, detents: [UISheetPresentationController.Detent], @ViewBuilder content: () -> Content) {
        self.label = label
        self.content = content()
        self.detents = detents
    }

    func makeUIView(context: UIViewRepresentableContext<BottomSheetPresenter>) -> UIButton {
        let button = UIButton(type: .system)

        // configure button

        return button
    }

    func updateUIView(_ uiView: UIButton, context: Context) {
        // no updates
    }

    func makeCoordinator() -> Void {
        return ()
    }
}

The bottom sheet presenter initializer takes three arguments, a label for the button, the detents (steps) that we want to use in our UISheetPresentationController, and the content that should be shown in the presented view controller.

Note that I had to make my BottomSheetPresenter generic over Content so it can take a @ViewBuilder that generates a View for the presented view controller. We can't use View as the return type for the @ViewBuilder because View has a Self requirement which means it can only be used as a generic constraint.

Tip:
To learn more about generics, associated types, and generic constraints take a look at this post. For an introduction to generics you might want to read this post first.

The BottomSheetPresenter is a UIViewRepresentable struct which means that it can be used to present a UIKit view in a SwiftUI context.

The makeUIView method is used to create and configure our UIButton. We don't need any extra information so the makeCoordinator method returns Void, and the updateUIView method can remain empty because we're not going to update our view (we don't need to).

Let's fill in the makeUIView method:

func makeUIView(context: UIViewRepresentableContext<BottomSheetPresenter>) -> UIButton {
    let button = UIButton(type: .system)
    button.setTitle(label, for: .normal)
    button.addAction(UIAction { _ in
        let hostingController = UIHostingController(rootView: content)
        let viewController = BottomSheetWrapperController(detents: detents)

        viewController.addChild(hostingController)
        viewController.view.addSubview(hostingController.view)
        hostingController.view.pinToEdgesOf(viewController.view)
        hostingController.didMove(toParent: viewController)

        button.window?.rootViewController?.present(viewController, animated: true)
    }, for: .touchUpInside)

    return button
}

The implementation for makeUIView is pretty straightforward. We assign the button's title and add an action for touch up inside.

When the user taps this button, we create an instance of UIHostingController to present a SwiftUI view in a UIKit context, and we pass it the content that was created by the initializer's @ViewBuilder closure. After that, we create an instance of BottomSheetWrapperController. This view controller will receive the UIHostingController as its child view controller, and it's the view controller we'll present. We need this extra view controller so we can override its viewDidLoad and configure the detents for its presentationController (remember how we presented a bottom sheet in UIKit?).

The following lines of code add the hosting controller as a child of the wrapper controller, and I set up the constraints using a convenient method that I added as an extension to UIView. The pinToEdgesOf(_:) function I added in my UIView extension configures my view for autolayout and it pins all edges to the view that's passed as the argument.

Once all setup is done, I present my wrapper controller on the button's window. This will make sure that this implementation works well in applications that support multiple windows.

Lastly, I return the button so that it can be presented in my SwiftUI view.

Before we look at the SwiftUI view, let's look at the implementation for BottomSheetWrapperController.

Implementing the BottomSheetWrapperController

The implementation for the BottomSheetWrapperController class is pretty straightforward. It has a custom initializer so we can accept the array of detents from the BottomSheetPresenter, and in viewDidLoad we check if we're being presented by a UISheetPresentationController. If we are, we assign the detents and set the grabber to be visible.

Note that you might want to make the grabber's visibility configurable by making it an argument for the initializer and storing the preference as a property on the wrapper.

class BottomSheetWrapperController: UIViewController {
    let detents: [UISheetPresentationController.Detent]

    init(detents: [UISheetPresentationController.Detent]) {
        self.detents = detents
        super.init(nibName: nil, bundle: nil)
    }

    required init?(coder: NSCoder) {
        fatalError("No Storyboards")
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        if let sheetController = self.presentationController as? UISheetPresentationController {
            sheetController.detents = detents
            sheetController.prefersGrabberVisible = true
        }
    }
}

I'm not going to go into the details of how this view controller works in this post. Please refer to the UIKit version of this post if you want to know more (it's very short).

Using the BottomSheetPresenter in SwiftUI

Now that we have everything set up, let's take a look at how the BottomSheetPresenter can be used in a SwiftUI view:

struct ContentView: View {
    var body: some View {
        BottomSheetPresenter("Tap me for a bottom sheet!!", detents: [.medium(), .large()]) {
            VStack {
                Text("This is a test")
                Text("Pretty cool, right")
            }
        }
    }
}

That doesn't look bad at all, right? We create an instance of BottomSheetPresenter, we assign it a label, pass the detents we want to use and we use regular SwiftUI syntax to build the contents of our bottom sheet.

I agree, it doesn't feel very at home and it would be nicer to configure the bottom sheet with a view modifier. This is exactly what Adam Foot implemented in his version of BottomSheet. The only downside to that version is that it grabs the first window it can find to present the sheet. This means that it wouldn't work well in an application with multiple windows. Other than that, I really like his custom SwiftUI modifier, and I would recommend you take a look at the implementation if you're curious.

You'll find that it's very similar to what you learned in this post, except it has a bunch more configuration that I didn't include during my exploration to see if I could get this bottom sheet to work.

Keep in mind, this post isn't intended to show you the ultimate way of achieving this. My goal is to help you see how I got to my version of using UISheetPresentationController in SwiftUI through experimentation, and applying what I know from presenting a UICloudSharingController in SwiftUI.

Presenting a bottom sheet in UIKit with UISheetPresentationController

We've seen bottom sheets in Apple's apps for a while now, and plenty of apps have followed this pattern. If you're not sure what I mean, it's the kind of sheet that takes up just a part of the screen and can be swiped upwards to take up the whole screen or downwards to be dismissed. Here's an example from Apple's Maps app:

To implement a sheet like this, we used to require third party tools, or we needed to get creative and implement this pattern ourselves.

With iOS 15, Apple introduced UISheetPresentationController which allows us to implement bottom sheets with just a few lines of code.

When you present a view controller as shown below, you know that your presented view controller will be shown as a "card" on top of the presenting view controller:

present(targetViewController, animated: true)

By default, the user can already swipe the presented view controller down to dismiss it interactively.

A view controller that is presented with present(_:animated:) on iOS 15 will have a UISheetPresentationController set as its presentation controller automatically. This presentation controller is responsible for managing the transition between the presented and the presenting view controller, and it handles interaction like interactive dismissal.

It also handles the bottom sheet behavior that we want to implement. So that our view controller will first take up half the screen, and then can be expanded to full height and back down again.

To implement this, you use so called detents. These detents are set on the UISheetPresentationController and will be used to determine how the view controller can be shown. We can choose between medium, large, or both. Using only a medium detent will make your presented view controller take up roughly half the height of the screen. A large detent is the default and it makes the presented view controller its full height. Using both will allow the user to swipe between medium and large.

Here's how you set the UISheetPresentationController's detents:

override func viewDidLoad() {
    super.viewDidLoad()

    if let sheetController = self.presentationController as? UISheetPresentationController {
        sheetController.detents = [.medium(), .large()]
    }
}

You simply check if the view controller's presentation controller is an instance of UISheetPresentationController, and if it is you assign its detents.

Apple's Maps implementation shows a nice grabber that indicates to users that they can drag the bottom sheet up or down. This grabber isn't shown by default so you'll need to enable it manually if you want it to be shown:

sheetController.prefersGrabberVisible = true

This new feature is very nice, and I love how easy Apple has made it to implement a bottom sheet in iOS 15.

Unfortunately, we can't (easily) use this feature in SwiftUI. But if you're interested in a workaround... I have one for you right here.

What are Swift Concurrency’s task local values?

If you've been following along with Swift Concurrency in the past few weeks, you might have come across the term "task local values". Task local values are, like the name suggests, values that are scoped to a certain task. These values are only available within the context they're scoped to, and they are really only supposed to be used in a handful of use cases.

In this post, I will explain what task local are, and more importantly I will explain how and when they are useful. For a full rundown of task local values and their design I'd like to refer you to SE-0311: Task Local Values.

Understanding what task local values are

Task local values are a way to associate some state with a Swift Concurrency Task, or rather a specific context within a Task. We can create a scope for a task local value to live in, even if we're already in a task (or a child task). This doesn't quite explain what a task local value is, and to really understand this we need to zoom out a little bit. If we don't, this entire feature will be really hard to understand.

When you create a new Task in Swift Concurrency, either through Task.init (formerly async), or Task.detached (formerly detach), this task will have a priority property and an isCancelled property. We can read these values by obtaining and inspecting the current task:

withUnsafeCurrentTask { task in
    print(task?.isCancelled)
    print(task?.priority)
}

The withUnsafeCurrentTask checks if the context we're currently in runs as part of a Task instance, and if it does, the "current" task (the task that we're part of) is provided to the closure. We can then read the isCancelled property to check if the current task is cancelled, allowing is to act accordingly.

You can imagine that writing this code everywhere would be tedious, so the Swift team provided a more convenient way to check if the current task is cancelled: Task.isCancelled. This static member on Task will obtain the current task for us, and it will return that task's cancellation status (or false if no current task exists). Here's what that static variable looks like:

extension Task {
    static var isCancelled: Bool {
        return withUnsafeCurrentTask { task in
            return task?.isCancelled ?? false
        }
    }
}

This static isCancelled property is not quite the same as a task local value, but it's close enough to proceed with understanding what they are. Remember that Task.isCancelled is a regular static property that returns a different value depending on which task it's accessed from.

With task local values, we can achieve a similar feature that allows us to associate metadata about a task with a task. We can do this by annotating a static property with the @TaskLocal property wrapper. This property wrapper will make sure that the given static property's value is only assigned within the scope of a given task.

Let's see what this looks like:

enum Transaction {
    @TaskLocal static var id: UUID? = nil
}

This enum has a task local id that can be used to identify a transaction in our system. I'll explain what this can be used for later. I want to explain task locals a little bit more before I show you how to use them.

My task local value has a default value of nil. This default value is the value that I'll get when I try to read the transaction id from a task that does not explicitly have its Transaction.id set. Note that after I assign a default value to my id, I can not change it:

Transaction.id = UUID() // Cannot assign to property: 'id' is a get-only property

To assign a task local value, we need to call a method on $id as follows:

await Transaction.$id.withValue(UUID()) {
    print(Transaction.id)
}

The withValue(_:operation:) method creates a scope where Transaction.id will have the provided value as its value. This works very similar to how Task.isCancelled is implemented. The value that's returned when accessing Transaction.id is determined by checking the context that we're currently in. If we're not in a context where the value was explicitly set we'll receive the default value that we assigned in the declaration. In this case that would be nil.

The value that's assigned to Transaction.id when creating a scope is only valid during that scope.

You can temporarily override this value within the scope with a nested call to withValue(_:operation:):

Transaction.$id.withValue(UUID()) {
    print(Transaction.id) // original value

    Transaction.$id.withValue(UUID()) {
        print(Transaction.id) // new value
    }

    print(Transaction.id) // original value
}

Outside of the nested closure, the value for Transaction.id returns it's "orginal" value because the assigned value is scoped to the closure that you pass to withValue.

The way Swift Concurrency scopes this makes sure that you can't accidentally assign an expensive object to a task local value and forget to deallocate it when it's no longer needed. In other words, the scoping of withValue(_:operation:) makes sure that our task local value does not escape its scope.

If we start a new detached task from within a context created through withValue(_:operation:) this task will not inherit the task local values that were present in the context:

Transaction.$id.withValue(UUID()) {
    print(Transaction.id) // assigned value

    Task {
        print(Transaction.id) // assigned value
    }

    Task.detached {
        print(Transaction.id) // nil
    }
}

If you want task local values to be copied into a detached task you'll need to explicitly copy this value:

Transaction.$id.withValue(UUID()) {
    let transaction = Transaction.id
    Task.detached {
        print(transaction) // the task local UUID
    }
}

You can also use this copied value as a new task local for the detached task:

Transaction.$id.withValue(UUID()) {
    let transaction = Transaction.id
    Task.detached {
        Transaction.$id.withValue(transaction) {
            print(Transaction.id) // the task local UUID from the outer scope
        }
    }
}

Note that this allows multiple sources to read this value concurrently. For this reason task local values have to be safe to use concurrently. This is enforced by the requirement that task local values are Sendable.

Okay. I think at this point you know enough about task local values to have an idea of what they are and how they're used. In short, they provide a scope where a certain "global" value is available.

Let's see when these values can (and more importantly should) be used.

Understanding how task local values can be used

When you've read the previous section, it might seem attractive to put shared state or information in a task local value. This would have a similar feel to SwiftUI's @Environment which is intended for sharing of state and dependencies in a view hierarchy.

Task local values are not intended to be used like this.

I feel like I should repeat this with different words.

Task local values should not be used to provide state that you depend on within the context of a task.

There are multiple reasons for this, and I reckon one most important ones is that it's extremely error prone to have to depend on setting this state outside of a function. It's easy to forget to call withValue(_:operation:) all the time, and this could mean that you introduce unnoticed bugs in your application.

Another, possibly more important, reason to not rely on task local values to provide state you depend on is that it's more expensive to look up task local values than it is to access a normal variable. The reason for this is that the task local value will have to reason about its current context before it can provide a value.

When you have an async function that depends on specific state to do its job, pass it to the function explicitly.

So what are task local value for then?

Well, they are intended to associate specific metadata with a given task. This means that task local values will mostly be useful if you want to debug your code, or if you want to be able to group a bunch of asynchronously produced logs together through something like a transaction ID.

Imagine that you have some object that can fetch user data. This object depends on a data provider, and the data provider relies on an Authorizer and Networking object to make authorized network requests.

We might have many concurrent calls in progress, and when you attempt to debug something in this flow, your logs might looks a little like this:

UserApi.fetchProfile() called
UserApi.fetchProfile() called
RemoteDataSource.loadProfile() called
RemoteDataSource.loadProfile() called
UserApi.fetchProfile() called
Authorizer.authorize(_ request: URLRequest) called
RemoteDataSource.loadProfile() called
Authorizer.authorize(_ request: URLRequest) called
Authorizer.accessToken() called
Authorizer.refreshToken(_ token: Token?) called
Authorizer.authorize(_ request: URLRequest) called
Authorizer.accessToken() called
Networking.load<T: Decodable>(_ request: URLRequest) called
Authorizer.accessToken() called
Networking.load<T: Decodable>(_ request: URLRequest) called
Networking.load<T: Decodable>(_ request: URLRequest) called

With this output it's impossible to see what the order of events is exactly. We don't know if the first loadProfile call lines up with the first load call, or whether it triggered the call to refreshToken.

Without task local values you might pass a UUID to every function, and pass the UUID down to the next functions so you can retrace your steps. With task local values, you can associate a transaction ID with your task using the Transaction.id from before so it propogates throughout your function calls automatically. Let's see what this looks like:

class UserApi {
    let dataSource: RemoteDataSource

    init(dataSource: RemoteDataSource) {
        self.dataSource = dataSource
    }

    func fetchProfile() async throws -> Profile {        
        return try await Transaction.$id.withValue(UUID()) {
            if let transactionID = Transaction.id {
                print("\(transactionID) UserApi.fetchprofile() called")
            }
            return try await dataSource.loadUserProfile()
        }
    }
}

To print useful information, we check if Transaction.id is set. In this case we've set it with withValue(_:operation:) on the line before but we still unwrap it properly. Next, I simply prefix my old print statement with the transaction ID.

In the loadUserProfile function, I can also access the transaction ID because it runs as part of the same task:

func loadProfile() async throws -> Profile {
    if let transactionID = Transaction.id {
        print("\(transactionID): RemoteDataSource.loadRandomNumber() called")
    }

    let request = try await authorizer.authorize(URLRequest(url: endpoint))
    return try await network.load(request)
}

This logic can be written in all of the subsequent function calls too. So we'd add this same code to the authorize, accessToken, refreshToken, and load methods. When we run the code with all of this in place, here's what the same output from earlier would look like:

3F0A1FD9-D55D-4015-A7D0-8B054A1CF7A9: UserApi.fetchProfile() called
98365B1C-4176-44DA-806A-2D2BCB787111: UserApi.fetchProfile() called
3F0A1FD9-D55D-4015-A7D0-8B054A1CF7A9: RemoteDataSource.loadProfile() called
98365B1C-4176-44DA-806A-2D2BCB787111: RemoteDataSource.loadProfile() called
F02A7024-0B84-454C-9E23-E3DA0F8E3558: UserApi.fetchProfile() called
3F0A1FD9-D55D-4015-A7D0-8B054A1CF7A9: Authorizer.authorize(_ request: URLRequest) called
F02A7024-0B84-454C-9E23-E3DA0F8E3558: RemoteDataSource.loadProfile() called
98365B1C-4176-44DA-806A-2D2BCB787111: Authorizer.authorize(_ request: URLRequest) called
3F0A1FD9-D55D-4015-A7D0-8B054A1CF7A9: Authorizer.accessToken() called
3F0A1FD9-D55D-4015-A7D0-8B054A1CF7A9: Authorizer.refreshToken(_ token: Token?) called
F02A7024-0B84-454C-9E23-E3DA0F8E3558: Authorizer.authorize(_ request: URLRequest) called
98365B1C-4176-44DA-806A-2D2BCB787111: Authorizer.accessToken() called
3F0A1FD9-D55D-4015-A7D0-8B054A1CF7A9: Networking.load<T: Decodable>(_ request: URLRequest) called
F02A7024-0B84-454C-9E23-E3DA0F8E3558: Authorizer.accessToken() called
98365B1C-4176-44DA-806A-2D2BCB787111: Networking.load<T: Decodable>(_ request: URLRequest) called
F02A7024-0B84-454C-9E23-E3DA0F8E3558: Networking.load<T: Decodable>(_ request: URLRequest) called

Now that every sequence of method calls is associated with a transaction id, the logs that are produced by this program are far more useful than they were before.

This is a really good use of task local values because we're not using them to pass around important state. Instead, we use this for logging and retracing our steps. The transaction ID really is metadata rather than state. This is exactly what the Swift team has intended task local values for. They're a container for task metadata.

In Summary

While task local values will most likely not be a heavily used feature for most people, I'm sure some developers will make heavy use of it for debugging, logging, and other purposes. I personally find this transaction example very compelling because I've worked on a codebase not too long ago where we passed transaction IDs around to every method call that would make a network call so we could collect comprehensive logs in case something went wrong. Manually passing a transaction ID around really feels like busywork, and being able to associate a transaction ID with an entire chain of method calls that occur withing the scope of the operation passed to withValue(_:operation:) is a breath of fresh air.

If you every find yourself needing to untangle a bunch of concurrently active tasks, task local values might just be the tool you need to help you out.

Got any questions or feedback? Feel free to shoot me a message on Twitter.

Actors in Swift explained with examples

Every since Apple announced a new Concurrency model in 2021, we've all been moving from completion handlers to async / await. That said, Swift Concurrency is much bigger than just async / await. It features a whole new Concurrency model that includes compile-time protection against data races, and new tools to prevent our code from having data races. On of these tools is Swift's Mutex which helps us create locks around mutable state. We also have global actors like Swift Concurrency's Main Actor to allow us to run code on the main actor. In Xcode 26, this has been made a default so that our code runs serially by default, and we can introduce concurrency when we need it. This makes code simpler, and also acts as a way to prevent us from unintentionally writing code that's concurrent when we don't need to be concurrent at all.

In this post, I'd like to talk about an entirely new type of object that was introduced alongside Swift Concurrency. We're going to talk about actors.

In this post you'll learn about the following:

  • Understanding the problem that actors solve
  • How to prevent data races without actors
  • Using actors to prevent data races

Understanding the problem that actors solve

An actor in Swift is an object that isolates access to its mutable state. This means that anybody that wants to access state or call a method on an actor, has to do so asynchronously.

But what does this mean? And why is this the case?

To answer that, let’s consider an example of code that you might write if you're avoiding actors:

class DateFormatterCache {
    static let shared = DateFormatterCache()

    private var formatters = [String: DateFormatter]()

    func formatter(with format: String) -> DateFormatter {
        if let formatter = formatters[format] {
            return formatter
        }

        let formatter = DateFormatter()
        formatter.locale = Locale(identifier: "en_US_POSIX")
        formatter.dateFormat = format
        formatters[format] = formatter
        return formatter
    }
}

This code is quite straightforward, and something that I have actually included in a project once. However, it got rejected in a PR. To find out why, let’s see how this code would be used.

Emulating concurrent access with DispatchQueue.concurrentPerform

Let’s emulate a situation where this code is used in a multithreaded environment.

Let’s add a few print statements first:

class DateFormatterCache {
    static let shared = DateFormatterCache()

    private var formatters = [String: DateFormatter]()

    func formatter(with format: String) -> DateFormatter {
        if let formatter = formatters[format] {
            print("returning cached formatter for \(format)")
            return formatter
        }

        print("creating new formatter for \(format)")
        let formatter = DateFormatter()
        formatter.locale = Locale(identifier: "en_US_POSIX")
        formatter.dateFormat = format
        formatters[format] = formatter
        return formatter
    }
}

This will tell us whether we’re reusing an existing formatter or creating a new one. These print statements will make it easier to follow what this code does exactly.

Here’s how I’ll emulate the multithreaded environment:

let formats = ["DD/MM/YYYY", "DD-mm-yyyy", "yyyy", "DD-MM", "DD-mm"]
DispatchQueue.concurrentPerform(iterations: 10) { iteration in
    let formatter = DateFormatterCache.shared.formatter(with: formats.randomElement()!)
}

I know these date formats might not be the best; it’s not the point for me to show you some clever date formats. Instead, I want to demonstrate a problem to you.

Running this code crashes most of the time for me. I get an EXC_BAD_ACCESS error on the formatters dictionary after a couple of iterations.

When looking at the console, the output looks a little like this:

creating new formatter for DD-mm-yyyy
creating new formatter for DD-mm
creating new formatter for DD-mm-yyyy
creating new formatter for yyyy
creating new formatter for DD-mm-yyyy
creating new formatter for DD-MM
creating new formatter for DD-MM
creating new formatter for DD-mm-yyyy
creating new formatter for DD-mm-yyyy
creating new formatter for DD/MM/YYYY

This makes it look like the cache is not doing anything. Clearly, we're creating a new formatter for every iteration.

Let’s run this code in a normal for loop to see if that’s any better.

for _ in 0..<10 {
    let formatter = DateFormatterCache.shared.formatter(with: formats.randomElement()!)
}

The first thing to note is that this code wouldn’t crash. There’s no bad access on formatters inside of the cache anymore.

Let’s look at the console:

creating new formatter for DD/MM/YYYY
creating new formatter for DD-mm-yyyy
returning cached formatter for DD/MM/YYYY
returning cached formatter for DD/MM/YYYY
creating new formatter for yyyy
returning cached formatter for DD/MM/YYYY
creating new formatter for DD-mm
returning cached formatter for yyyy
returning cached formatter for DD-mm
returning cached formatter for DD-mm

This looks much better. Apparently the caching logic should work. But not when we introduce concurrency…

Understanding why data races happen

The reason the formatter cache crashed in the concurrent example is a data race. Multiple threads attempt to read, and modify, the formatters dictionary. The program can’t handle these concurrent reads and writes which puts our program in an inconsistent state and eventually leads to a crash.

Another interesting aspect of this is the broken cache. This of course related to the data race, but let’s see what actually happens when the code runs.

I have explained issues with concurrency, mutable state, and dictionaries before in this post.

Because we’re running code concurrently, we call the formatter(with:) method ten times at roughly the same time. When this functions starts, it reads the formatters dictionary which will be empty, so no formatters are cached. And because we have ten concurrent reads, the dictionary will be empty for each of the ten calls.

Dictionaries are passed by value with reference characteristics. This means that the dictionary is not copied until you attempt to modify it. This is important to remember.

When each of the ten calls to formatter(with:) attempt to add the newly created formatter to the cache, the formatter will be copied and the new value is added to the copy. This means that each iteration will be adding to the dictionary that was read earlier. An empty dictionary that we'll add one entry to, and we'll make that the new value of formatters. This means that we'll end up with a different dictionary that has one value after each of these concurrent function calls.

Usually.

Because our concurrent code might also run slightly slower, we could sometimes have a dictionary with two, three, or more items. And this dictionary could be overwritten by a later iteration if our code happens to run that way.

There’s a ton of ambiguity here. We don’t control exactly how our formatter cache is accessed, by which thread, and how often. This means that my initial, simple implementation, can never work reliably in a multithreaded environment.

Solving data races without Actors

We can fix this without Swift’s new concurrency by synchronizing access to the formatters dictionary. Synchronizing means that we ensure that we execute the formatter(with:) function serially even if it’s called in parallel. This will ensure that the formatters dictionary is read, and updated, atomically. Or in one pass. Or in other words, without interruption. To gain a better understanding of what atomicity is, you can refer to this post I wrote earlier. By synchronizing code we'll know that once the formatter(with:) function has done its work, we’re ready to handle another call to formatter(with:). Basically callers to formatter(with:) will have to wait for their turn.

Synchronizing code like that can be done with a dispatch queue:

class DateFormatterCache {
    static let shared = DateFormatterCache()

    private var formatters = [String: DateFormatter]()
    private let queue = DispatchQueue(label: "com.dw.DateFormatterCache.\(UUID().uuidString)")

    func formatter(with format: String) -> DateFormatter {
        return queue.sync {
            if let formatter = formatters[format] {
                print("returning cached formatter for \(format)")
                return formatter
            }

            print("creating new formatter for \(format)")
            let formatter = DateFormatter()
            formatter.locale = Locale(identifier: "en_US_POSIX")
            formatter.dateFormat = format
            formatters[format] = formatter
            return formatter
        }
    }
}

By creating a private queue and calling sync on it in the formatter, we make sure the queue only runs one of these closures at a time. We can return the result of our operation from the closure, by returning queue.sync from the function because everything happens synchronously.

While this code runs we block the calling thread. This means that nothing else can run on that thread until the sync closure ran.

When we run the concurrent example code again with this private queue in place:

let formats = ["DD/MM/YYYY", "DD-mm-yyyy", "yyyy", "DD-MM", "DD-mm"]
DispatchQueue.concurrentPerform(iterations: 10) { iteration in
    let formatter = DateFormatterCache.shared.formatter(with: formats.randomElement()!)
}

It doesn’t crash and produces the following output:

creating new formatter for DD/MM/YYYY
returning cached formatter for DD/MM/YYYY
creating new formatter for yyyy
creating new formatter for DD-mm
returning cached formatter for DD-mm
creating new formatter for DD-mm-yyyy
returning cached formatter for DD/MM/YYYY
returning cached formatter for yyyy
returning cached formatter for DD-mm
creating new formatter for DD-MM

Clearly, the code works well! Awesome.

But there are a few problems here:

  1. We block the thread. This means that GCD will spawn new threads to make sure the CPU stays busy with those threads instead of sitting completely idle. This means that we’ll potentially have tons of threads, which can be expensive if the CPU has to context switch between threads a lot.
  2. It’s not clear to the caller of formatter(with:) that it’s a blocking function. A caller of this function might have to wait for many other calls to this function to complete which might be unexpected.
  3. It’s easy to forget synchronization, especially if the formatters property should be readable from outside of the class. The compiler can’t help us so we have to rely on our own judgement and hope that any mistakes get caught in PR, just like my mistake was.

In modern Swift code, we can leverage actors to achieve proper mutable state isolation with compiler support.

Solving data races with Actors

As I mentioned earlier, actors isolate access to their mutable state. This means that an object like the DateFormatterCache can be written as an actor instead of a class, and we’ll get synchronization for free:

actor DateFormatterCache {
    static let shared = DateFormatterCache()

    private var formatters = [String: DateFormatter]()

    func formatter(with format: String) -> DateFormatter {
        if let formatter = formatters[format] {
            print("returning cached formatter for \(format)")
            return formatter
        }

        print("creating new formatter for \(format)")
        let formatter = DateFormatter()
        formatter.locale = Locale(identifier: "en_US_POSIX")
        formatter.dateFormat = format
        formatters[format] = formatter
        return formatter
    }
}

Note how the object is completely unchanged from the initial version. All I did was change class to actor and I removed the queue that we added later. Also note that actors are reference types, just like classes are.

Now that DateFormatterCache is an actor, Swift will know that formatters is mutable and that any access to it will need to be synchronized. This also means that Swift knows hat formatter(with:) might not return immediately, even if the function isn’t marked async. This is very similar to what we had earlier with the private queue.

If I were to make formatters an internal or public property instead of private, accessing formatters directly from the outside would also be synchronized, and therefor be done asynchronously from the caller’s point of view.

Within the actor, we know that we’re already synchronized. So I don’t have to wait for formatters’s value to be read. I can just read it directly without doing any manual synchronization. I get all of this for free; there’s no work to be done by me to ensure correct synchronization.

Running the following test code from earlier produces an error though:

let formats = ["DD/MM/YYYY", "DD-mm-yyyy", "yyyy", "DD-MM", "DD-mm"]
DispatchQueue.concurrentPerform(iterations: 10) { iteration in
    let formatter = DateFormatterCache.shared.formatter(with: formats.randomElement()!)
}

Here’s the error:

Actor-isolated instance method ‘formatter(with:)’ can only be referenced from inside the actor

This error seems to suggest that we cannot access formatter(with:) at all. This isn’t entirely correct, but we’ll need access it asynchronously rather than synchronously like we do now. The easiest way to do this is to either already be in an async context, or enter one:

let formats = ["DD/MM/YYYY", "DD-mm-yyyy", "yyyy", "DD-MM", "DD-mm"]
DispatchQueue.concurrentPerform(iterations: 10) { iteration in
    Task {
        let formatter = DateFormatterCache.shared.formatter(with: formats.randomElement()!)
    }
}

Doing this provides us with a more useful compiler error:

Expression is ‘async’ but is not marked with ‘await’

Remember how I explained that formatter(with:) might not return immediately because it will be synchronized by the actor just like how the queue.sync version in the class didn’t return immediately?

In the old version of this code, the blocking nature of formatters(with:) was hidden.

With an actor, the compiler will tell us that formatter(with:) might not return immediately, so it forces us to use an await so that our asynchronous work can be suspended until formatter(with:) is run.

Not only is this much nicer due to the more expressive nature of the code, it’s also much better because we’re not blocking our thread. Instead, we’re suspending our function so its execution context can be set aside while the existing thread does other work. We don't create a new thread like we did with GCD. Eventually the actor runs formatter(with:) and our execution context is picked back up where it left off.

Here's what the corrected code looks like:

let formats = ["DD/MM/YYYY", "DD-mm-yyyy", "yyyy", "DD-MM", "DD-mm"]
DispatchQueue.concurrentPerform(iterations: 10) { iteration in
    Task {
        let formatter = await DateFormatterCache.shared.formatter(with: formats.randomElement()!)
    }
}

What’s interesting is that because Swift’s new concurrency model does not spawn more threads than CPU cores, simply wrapping the class based version of the cache in a Task.init or Task.detached block would already mask our bug most of the time. The reason for this is that it’s very likely that all of the task you create run on the same thread. This means that they won’t actually run concurrently like they do with Task.

You can try this out by making DateFormatter a class again and removing the await from the last code snippet. Keep the Task though since that will leverage Swift's new concurrency features.

However, you should not assume that the bug would actually be fixed by using a class, not synchronizing, and using Task. There is no guarantee that your closures would run on the same thread. And more importantly, in the really world you might have many tasks happening that are spawned from many different threads. This would make it far more likely for data races to occur than it is in my simple example.

Actors downsides and when you might want to avoid them

While actors are an incredibly useful tool, they're not without problems of their own. For example, if you're thinking of actors as a serial queue you might be in for a rude awakening when you run into actor reentrancy. Reentrancy is a feature of actors that allows them to perform work while awaiting something else. I always like to say that actors only do one thing at a time, but they won't sit around and do nothing when they could be doing something else.

On top of that, adding an actor to an existing codebase means that you're introducing a whole new isolation context into your codebase. In other words, you're adding a lot of concurrency because all interactions with the actor must be treated as asynchronous.

Alternatives to actors in modern Swift code

Whenever you're looking at solving data races, your primary objective is really to make your objects Sendable. When an object is Sendable, it's safe to interact with this object from multiple isolation contexts concurrently. In other words, a Sendable object is thread-safe.

Actors are, by definition, Sendable. But we can also make our classes and structs Sendable.

It's worth considering using a Mutex on mutable state instead of using an actor for objects where you're really only looking to protect a single property from data races. Our DateFormatterCache is a good example of this. If we had used a Mutex instead of an actor, the API would be just as safe but interacting with our cache is much simpler. The DateFormatterCache can be marked as Sendable once we use a Mutex, and the compiler will verify that DateFormatterCache meets all requirements for sendability for us.

Another alternative to using an actor is to apply an @MainActor annotation to your object. If you're working on a project created with Xcode 26, this is actually done automatically by default. By running certain parts of your code on the main actor by default, you can be certain that your code won't have data races; the main actor will protect state just like any other actor would. Marking something as @MainActor makes most sense for objects that you use in your UI. A DateFormatterCache might actually be a decent candidate to run on the main actor by default when you use it to prepare date strings for being displayed to the user.

For objects that aren't UI adjacent, an @MainActor annotation makes less sense; code would run on the main actor and interacting with it from a background thread would be asynchronous which is what you were trying to avoid by considering an alternative to actors.

In Summary

In this post, we explored Swift's Actors. You learned about the problems they solve, and how they solve these problems. You also learned that actors create their own isolation context which means that all interactions with an actor are asynchronous.

Next, I explored some alternatives to actors that you can rely on when you're only protecting some simple data from data races and you don't want to introduce concurrency everywhere that you interact with your actor.

WWDC Notes: Swift concurrency: Behind the scenes

Meet async / await, explore structured concurrency, protect mutable state with actors should be watched first.

Threading model

Compares GCD to Swift. It’s not built on top of GCD. It’s a whole new thread pool.

GCD is very eager to bring up threads whenever we kick off work on queues. When a queue blocks its thread, a new thread will be spawned to handle work.

This means that the system can overcommit with more threads than there are CPU cores. This is also called Thread explosion and can lead to memory and performance issues.

There’s a lot of scheduling overhead during threads. There will likely be a ton of context switching which in turn will make the CPU run less efficiently.

Swift concurrency was designed to be more efficient than GCD.

The goal is to have no more threads than CPU cores. Instead, there are continuations that can be blocked. Instead of having the CPU context switch, the thread does this. It’s as simple as a method call so the overhead is much, much lower.

To make this happen, the language has to be able to guarantee that threads do not block through language features:

  • await and non-blocking of threads
  • Tracking of dependencies in Swift task model

Swift’s await does not block a thread like GCD’s sync does.

Every thread has a stack that keeps track of function calls. There are several stack frames. One for each function call. When a function returns, its stack frame is popped.

When an async function is called with await, it’s tracked as an async frame on the heap. The async frames keep track of state that’s needed when the awaited function returns. When another function is called, the topmost stack frame on the thread is replaced. Because async frames are stored on the heap, they can be put back on a thread and resumed. Async frames will be put back on the stack as needed. Calling sync code in an async fuck will add frames to the thread’s stack.

The block of code that runs after the await is called a continuation When execution should resume, the continuation is put back on a thread’s stack.

Interesting stuff, try to find out more and properly understand this.

Async work is modeled with tasks. Tasks can have child tasks. Tasks can only await other tasks in swifts. Awaited tasks are either continuations or child tasks.

Threads can track these task dependencies and they’ll know how to suspend tasks and schedule other work until the task can be resumed.

A cooperative thread pool is the default executor for Swift. The number of threads is limited to the number of CPU cores. Threads will always make forward progress and avoids thread explosion and excessive task switching.

Where with GCD you needed to be mindful of the number of queues you use, Swift concurrency ensures that you don’t have to worry about this anymore.

Concurrency always comes with a cost. It takes additional memory allocation and logic in the Swift runtime. Concurrency should only be used when its cost outweighs the cost of managing it.

For example, reading for user defaults is a super small task that should not be spawned into its own async task unless needed.

Measure performance to understand when you need concurrency.

await explicitly breaks atomicity because in the time between your await and calling the continuation, things might change. You should never hold locks across await. Thread specific data is also not preserved across await because you might resume on a different thread than the one you were suspended on.

The Swift language upholds the runtime contract that threads can always make forward progress. You have to make sure you don’t break this contract so the thread pool can do its best work.

  • Use primitives like await, actors, and task groups so the compiler can enforce the contract.
  • Locks can be used in sync code with caution. There’s no compiler support but does not break the contract as long as the thread is not fully blocked (for too long)
  • Semaphores and NSCondition are not safe to use. They hide dependency information from the runtime so it cannot schedule work correctly which might result in blocking.

Don’t use unsafe primitives to wait across task boundaries. Like for example using a semaphore in an async context. This is not save.

The LIBDISPATCH_COOPERATIVE_POOL_STRICT=1 environment variable will run the app under a debug runtime that enforces forward progress for thread.

Synchronization with Actors

Actors synchronize access to their state through mutual exclusion.

When using DispatchQueue.sync, a current thread can be reused when there’s no contention. When there is, DispatchQueue.sync is blocking and new threads are spawned.

When you use DispatchQueue.async, you’re non-blocking under contention, but a new thread is always spawned.

Swift Actors always reuse threads and are non-blocking. If the thread is free, code is run. If not, function is suspended and run later.

Serial queues can be replaced with actors to manage access.

When you switch between different actors, you are thread hopping. An actor can be suspended and threads can easily hop from a running actor to a currently suspended actor. The runtime can handle this by creating work items for the thread without spawning a new thread.

Actor work items can remain pending until an in progress work item is completed.

Actors are designed to allow the system to prioritize work.

Actor reentrancy means that an actor might have pending work when it schedules and executes new work items. This can happen if a task is awaiting something, and this other thing awaits something on the actor.

The main actor runs on the main thread. The main thread is separated from the rest of the threads in the cooperative pol.

When you hop on and off the main actor often, you force hopping from and to the mean thread. This is expensive. If this happens it’s better to bundle work and run a bigger task to update UI from the main actor. For that reason, it’s not adviced to jump onto an actor and away from the main actor for small bits of work (often).

WWDC Notes: Bring Core Data concurrency to Swift and SwiftUI

Persistence everywhere

Core Data takes care of many complexities to persist data. It converts in-memory graph to persisted data and takes care of all kinds of complex tasks like memory management.

Core Data works on all platforms, and it’s great in Swift. Apple’s been working to make Core Data better with Swift over the years.

Core Data has always cared about running code concurrently.

Swift concurrency

Sample app

The sample app loads data from the background and persist it. Eventually it updates the view context.

Insertion is done with bgctx.performAndWait() and a batch insert.

performAndWait will block the calling thread to run the provided code on the context’s thread. The perform function doesn’t block and runs the code on the contexts queue.

You can use await ctx.perform {} to suspend the current execution context, have Core Data run code on its queue, and hand back control. Its usage is the same but intent is clearer without blocking.

In iOS 15, perform is generic over the returned type of object and the supplied closure can throw. This is nice and inline with async / await .

try await ctx.perform {
  throw SomeError.case
}

We used to obtain results like this:

var count: Int!
ctx.perform {
  // configure a request with NSCountResultTyoe
  count = request.execute().last!
}

With async / await we can do:

let count = try await ctx.perform {
  // configure a request with NSCountResultTyoe
  return request.execute().last!  
}

This is much nicer to read and reason about.

Returning a managed object from a perform can be risky. When you return a managed object from perform it’s not save to interact with the returned object.

Instead, you should return a managed object ID or dict representation.

Perform is scheduled with .immediate by default. It behaves a lot like an async version of performAndWait.

If you use enqueued, the work is always added to the end of the queue of the context. Even if you’re already in the correct context.

Translation to async await:

  • performAndWait == await perform
  • perform == await perform(.enqueued)

NSPersistentContainer and NSPersistentStoreCoordinator can also perform work in their context and have received similar async features.

Existing debugging tools still work and should be used.

CloudKit sharing is new and Core Data spotlight integration is improved.

Persistent stores are where data is stored. Core Data supplies XML, Binary, In Memory, and SQLite. On iOS 14 and below we used long names. Now they’re Swfty. .xml, .sqlite, etc.

AttributeType is also improved.

SwiftUI

@FetchRequest now has lazy entity resolution and they pick up dynamic configuration. There’s also a new sectioned fetch request.

Lazy entity resolution means you don’t have to set up the Core Data stack when creating your fetch request. Instead, it needs to be set up when the request is performed.

Predicates and Sort Descriptors can now be updated through properties on the wrapped value of the fetch request. Updating the property automatically reloads.

There’s also a new SortDescriptor type that’s easier to use.

@SectionedFetchRequest takes a sectionIdentifier that’s used to determine which section items are in. This fetch request returns a 2D array that represents sections with items for a section as its nested result.

The sectionIdentifier key path can be dynamically adjusted as well.

When changing a sortDescriptor, you might have to change the sectionIdentifier too.

WWDC Notes: Discover concurrency in SwiftUI

When performing slow work, you might dispatch off of the main queue. Updating an observable object off of the main queue could result in this updating colliding with a “tick” of the run loop. This means that SwiftUI receive an objectWillChange, and attempt to redraw UI before the underlying value is updated.

This will lead to SwiftUI thinking that your model is in one state, but it’s in the next.

SwiftUI needs to have objectWillChange->stateChange->runloop tick in this exact order.

Running your update on the main actor (or main queue pre async/await) will ensure that the state change is completed before the runloop tick since the operation would be atomic.

You can use await to ensure this. Doing this is called yielding (to) the main actor.

When you’re on the main actor and you call a function with await, you yield the actor, allowing it to do other work. The work is then performed by a different actor. When this work completes, control is handed back to the main actor where it will update state:

class Photos: ObservableObject {
  @Pulished var items: [SpacePhoto] = []

  func update() async {
    let fetched = await fetch() // yields main actor
    items = fetched // done on the main actor
  }
}

There’s currently guarantee that item is always accessed on the main actor. To make this guarantee, class Photos needs the @MainActor annotation.

The task modifier on a SwiftUI is used to run an async task on creation. It’s called at the same point in the lifecycle as onAppear.

Since task is tied to the view’s lifecycle, you can await an async sequence’s elements in task and rest assured that everything is cancelled and cleaned up when the view’s lifecycle ends.

Button methods in SwiftUI are synchronous. To launch an async task from a button handler, use async {} (will be renamed to Task.init) and await your async work.

Button("Save") {
  async {
    isSaving = true
    await model.save()
    isSaving = false
  }
}

In this button isSaving is mutated on the main actor. async (or Task.init) runs its task attached to the current actor. In a SwiftUI view, this would be the main actor. await will yield the main actor and run code on whatever actor model.save() runs until control is yielded back to the main actor.

The .refreshable modifier on SwiftUI takes an async closure. You can await an update operation in there. This modifier will, by default, use a pull to refresh control.

SwiftUI integrates nicely with async / await and asynchronous functions.

It’s recommended to mark ObservableObject with @MainActor to ensure that their property access and mutations are done savely on the main actor.

WWDC Notes: Meet AsyncSequence

Map, filter, reduce, dropFirst all work in async sequences:

for try await someThing in async.dropFirst() {
}

For example.

AsyncSequence suspends on each element and receives values asynchronously from the iterator. AsyncSequences either complete with success or stop when an error is thrown.

Implementing an AsyncSequence follows all the rules that a normal sequence follows. Its next() returns nil when it’s completed for example.

An async iterator also consumes its underlying collection.

Things like break and continue work in async sequences too.

You can cancel an iteration by holding on to its Task.Handle when you wrap it in async:

let handle = async {
  for await thing in list {
    // ...
  }
}

handle.cancel()

Reading files from a URL is commonly done async. You can use URL.lines for this. It works for network and local resources.

URLSession has a bytes(_:) function to enable roughly the same but with more control.

NotificationCenter notifications can be awaited too. You can even await one notification:

// listens for 1 notification only
let center = NotificationCenter.default
let notification = await center.notifications(named: .SomeNotification).first { notification in 
  print(notification)
}

Callbacks that are called multiple times, and some delegates are good candidates for async sequences.

Start / stop / handle pattern is a good candidate. Sounds similar to location managers.

let stream = AsyncStream(Output.self) { continuation in 
  let object = SomeObject()
  object.handler = { element in 
    continuation.yield(element)
  }

  object.onTermination = { _ in 
    object.stop()
  }

  // starts producing values
  object.start()
}

AsyncStream is the easiest way to create your own asynchronous sequences. They also handle buffering (not sure what that means in this case).

There’s also a throwing version: AsyncThrowingStream.

Note: AsyncStream does not appear to be present in Beta 1

WWDC Notes: What’s new in SwiftUI

A good way to get started with SwiftUI is to use it for new features. SwiftUI can be mixed in with UIKit and AppKit code. It also allows you to expand into new platforms, like macOS, with little to no work.

Essentially, try to do new work with SwiftUI whenever you can.

Better lists

SwiftUI can load images async with the new AsyncImage. This takes a URL and shows a placeholder by default. You can pass a closure to configure the loaded image with modifier, and to set a custom placeholder.

There’s a new refreshable modifier. This modifier takes a closure that takes an async closure. So you can await things in there. Lists use this modifier to add pull to refresh.

You can run a task on appear with the task modifier. This will run when the view is first created, and cancels the task when the view disappears. You could use this to fetch initial data for the list without blocking your UI.

Videos:

  • Discover concurrency in SwiftUI
  • Swift concurrency: Update a sample app

Text can be made editable with a TextField. This takes a binding but we might not easily have a binding available because in a list we receive an element; not a bindable object.

This is covered in depth in Demystifying SwiftUI.

You can pass a binding to your collection to the List. This will make it so the item closure receives a binding too. You can still read data like you did normally but you also have a binding.

Looks like you should use $thing instead of thing in the list item closure.

Separator tints can be set with listRowSeparatorTint. Also works for section separators. listRowSeparator(.hidden) hides the separators.

SwiftUI now has a swipeActions modifier that allows you to add swipe actions to items in ForEach. You can pass an edge to swipeAction to control where they appear. Also works on macOS.

View styles now have an enum-like style. For example listStyle(.inset). We can now pass a value to inset to alternate row background colors.

Beyond lists

We can now create tables with the Table view. Tables use a TableColumn for columns. They take a title + data. They support single + multiple selection and sorting. You can sort through key paths. Worth exploring, looks fun.

Fetch requests now provide a binding to their sort descriptor that allows you to sort fetched results Must explore

We can also use @SectionedFetchRequest to split @FetchRequest into sections.

Videos:

  • SwiftUI on the Mac: Fundamentals
  • SwiftUI on the Mac: Finishing touches
  • Bringing Core Data concurrency to Swift and SwiftUI

Lists in SwiftUI can now be made searchable through a modifier. It binds to a search query. There’s a whole session on each in SwiftUI.

We can use onDrag to make this draggable (existing) we can provide a preview: closure to provide a custom preview of the dragged data.

We can add the importsItemProviders to make a view a drop target that accepts item providers. We can add ImportFromDevicesCommands() to an app’s commands to allow import from external devices like a camera.

We can use exportsItemProviders modifier to export items so that apps like Shortcuts can use our data. Not sure how this works exactly though. Covered only very briefly.

Advanced graphics

Apple added lots of new SF Symbols and two new rendering modes. Hierarchical and palette. More information in the SF Symbols talk.

There are all kinds of new colors in SwiftUI this year.

SF Symbol variants are now automatically picked by the system. Modifiers like .fill or no longer needed. The correct variant is automatically chosen based on context and platform. This is covered more in the SwiftUI + SF Symbols talk.

A Canvas can be used to draw a large number of items that don’t need to be managed individually. It’s possible to add gestures to a Canvas and modify its contents. You can add accessibility information like accessibillityChildren to enhance the accessibility experience.

You can wrap a TimelineView to create a timeline loop to build a screensaver like experience for tvOS. Or you can even use it to update your watch app when it’s in the always on state. You could, for example, update your view every minute. More information in What’s new in WatchOS 8.

.privacySensitive is a useful modifier to hide views when they might be visible to others. For example when a device is locked.

Materials can be used to build blurry translucent backgrounds and more. Materials work with the safe area inset to build partial overlays for example. The Rich graphics session covers this in depth.

SwiftUI previews can now show landscape iOS devices. Accessibility modifiers are now shown in the inspector when using previews. You can also inspect the state of your accessibility with previews. Covered in depth in the accessibility session.

Text and keyboard (focussed based)

SwiftUI Text now supports markdown to format text and even include links or code. This is built on top of Swift Attributed strings. More information on this in What’s new in Foundation.

Xcode 13 can now extract localization catalogs at compile time. Check out Localize your SwiftUI app for more.

Dynamic type was already supported. Now we can set a dynamicTypeSize minimum and maximum size to ensure our layouts don’t break for too large or small texts.

We can enable text selection on macOS with .textSelection. All text within the view this is applied to will be selectable. Also works on iOS.

We can easily format dates with .formatted. We can even use this to format people names for example. We can bind text fields to formatted fields. PersonNameComponents is used in an example. Also covered in the Foundation talk.

We can use onSubmit to handle pressing of the return key. We can also apply this on an entire form. We can set the label of the return key through the submitLabel modifier.

We can add toolbars to a keyboard through the toolbar modifier by returning a ToolbarItemGroup with placement: .keyboard. Shown above keyboard on iOS/iPadOS and Touch Bar on Mac.

We use @FocusState to control focus state. The focused modifier takes a binding to a focus state and will change this state when something is focused. This allows you to update something else in your view.

@FocusState can represent a Hashable value and .focused($focusField, equals: .addAttendee) to for example bind to an enum value.

When you set the @FocusState property to a value, the view that has its focused(_:equals:) set to that value will be activated.

Keyboard can be dismissed by not having a selected focus state. More information in the SwiftUI + Focus session.

Buttons

Buttons are used all over the place in SwiftUI. You can use the .bordered button style to add a button around buttons. You can add tinting and apply the modifier to a container to style all buttons.

You can use controlSize and controlProminence to set a button’s styling too. A button that has an increased prominence gets high contrast color to stand out. accentColor is more dimmed. Button size .large makes a large full width button.

You can use a maxWidth to prevent a button from being too big. You can apply a keyboardShortcut to activate a button.

High prominence should not be applied to all buttons. It’s best for 1 button per screen. A lower prominence can be used to add a splash of color. You can mark buttons as destructive now so they are colored red. You can also ask confirmation for (destructive only?) buttons with the confirmationDialog.

Menu on macOS can now have a primary action and a menu with options of secondary actions. This also works on iOS.

New on button is a toggle style to activate / deactivate buttons.

We can compose everything together in a control group for example.