Writing custom property wrappers for SwiftUI

It's been a while since I published my post that helps you wrap your head around Swift's property wrappers. Since then, I've done more and more SwiftUI related work and one challenge that I recently had to dig into was passing dependencies from SwiftUI's environment into a custom property wrapper.

While figuring this out I learned about the DynamicProperty protocol which is a protocol that you can conform your property wrappers to. When your property wrapper conforms to the DynamicProperty protocol, your property wrapper will essentially become a part of your SwiftUI view. This means that your property wrapper can extract values from your SwiftUI environment, and your SwiftUI view will ask your property wrapper to update itself whenever it's about to evaluate your view's body. You can even have @StateObject properties in your property wrapper to trigger updates in your views.

This protocol isn't limited to property wrappers, but for the sake of this post I will explore DynamicProperty in the context of a property wrapper.

Understanding the basics of DynamicProperty

Defining a dynamic property is as simple as conforming a property wrapper to the DynamicProperty protocol. The only requirement that this protocol has is that you implement an update method that's called by your view whenever it's about to evaluate its body. Defining such a property wrapper looks as follows:

@propertyWrapper
struct MyPropertyWrapper: DynamicProperty {
  var wrappedValue: String

  func update() {
    // called whenever the view will evaluate its body
  }
}

This example on its own isn't very useful of course. I'll show you a more useful custom property wrapper in a moment. Let's go ahead and take a moment to explore what we've defined here first.

The property wrapper that we've defined here is pretty straightforward. The wrapped value for this wrapper is a string which means that it'll be used as a string in our SwiftUI view. If you want to learn more about how property wrappers work, take a look at this post I published on the topic.

There's also an update method that's called whenever SwiftUI is about to evaluate its body. This function allows you to update state that exists external to your property wrapper. You’ll often find that you don’t need to implement this method at all unless you’re doing a bunch of more complex work in your property wrapper. I’ll show you an example of this towards the end of the article.

⚠️ Note that I’ve defined my property wrapper as a struct and not a class. Defining a DynamicProperty property wrapper as a class is allowed, and works to some extent, but in my experience it produces very inconsistent results and a lot of things you might expect to work don’t actually work. I’m not quite sure exactly why this is the case, and what SwiftUI does to break property wrappers that were defined as classes. I just know that structs work, and classes don’t.

One pretty neat thing about a DynamicProperty is that SwiftUI will pick it up and make it part of the SwiftUI environment. What this means is that you have access to environment values, and that you can leverage property wrappers like @State and @ObservedObject to trigger updates from within your property wrapper.

Let’s go ahead and define a property wrapper that hold on to some state and updates the view whenever this state changes.

Triggering view updates from your dynamic property

Dynamic properties on their own can’t tell a SwiftUI view to update. However, we can use @State, @ObservedObject, @StateObject and other SwiftUI property wrappers to trigger view updates from within a custom property wrapper.

A simple example would look a little bit like this:

@propertyWrapper
struct CustomProperty: DynamicProperty {
    @State private var value = 0

    var wrappedValue: Int {
        get {
            return value
        }

        nonmutating set {
            value = newValue
        }
    }
}

This property wrapper wraps an Int value. Whenever this value receives a new value, the @State property value is mutated, which will trigger a view update. Using this property wrapper in a view looks as follows:

struct ContentView: View {
    @CustomProperty var customProperty

    var body: some View {
        Text("Count: \(customProperty)")

        Button("Increment") {
            customProperty += 1
        }
    }
}

The SwiftUI view updates the value of customProperty whenever a button is tapped. This on its own does not trigger a reevaluation of the body. The reason our view updates is because the value that represents our wrapped value is marked with @State. What’s neat about this is that if value changes for any reason, our view will update.

A property wrapper like this is not particularly useful, but we can do some pretty neat things to build abstractions around different kinds of data access. For example, you could build an abstraction around UserDefaults that provides a key path based version of AppStorage:

class SettingKeys: ObservableObject {
    @AppStorage("onboardingCompleted") var onboardingCompleted = false
    @AppStorage("promptedForProVersion") var promptedForProVersion = false
}

@propertyWrapper
struct Setting<T>: DynamicProperty {
    @StateObject private var keys = SettingKeys()
    private let key: ReferenceWritableKeyPath<SettingKeys, T>

    var wrappedValue: T {
        get {
            keys[keyPath: key]
        }

        nonmutating set {
            keys[keyPath: key] = newValue
        }
    }

    init(_ key: ReferenceWritableKeyPath<SettingKeys, T>) {
        self.key = key
    }
}

Using this property wrapper would look as follows:

struct ContentView: View {
    @Setting(\.onboardingCompleted) var didOnboard

    var body: some View {
        Text("Onboarding completed: \(didOnboard ? "Yes" : "No")")

        Button("Complete onboarding") {
            didOnboard = true
        }
    }
}

Any place in the app that uses @Setting(\.onboardingCompleted) var didOnboard will automatically update when the value for onboarding completed in user defaults updated, regardless of where / how this happened. This is exactly the same as how @AppStorage works. In fact, my custom property wrapper relies heavily on @AppStorage under the hood.

My SettingsKeys object wraps up all of the different keys I want to write to in UserDefaults, the @AppStorage property wrapper allows for easy observation and makes it so that I can define SettingsKeys as an ObservableObject without any troubles.

By implementing a custom get and set on my Setting<T>'s wrappedValue, I can easily read values from user defaults, or write a new value simply by assigning to the appropriate key path in SettingsKeys.

Simple property wrappers like these are very useful when you want to streamline some of your data access, or if you want to add some semantic meaning and ease of discovery to your property wrapper.

To see some more examples of simple property wrappers (including a user defaults one that inspired the example you just saw), take a look at this post from Dave Delong.

Using SwiftUI environment values in your property wrapper

In addition to triggering view updates via some of SwiftUI’s property wrappers, it’s also possible to access the SwiftUI environment for the view that your property wrapper is used in. This is incredibly useful when your property wrapper is more complex and has a dependency on, for example, a managed object context, a networking object, or similar objects.

Accessing the SwiftUI environment from within your property wrapper is done in exactly the same way as you do it in your views:

@propertyWrapper
struct CustomFetcher<T>: DynamicProperty {
    @Environment(\.managedObjectContext) var managedObjectContext

    // ...
}

Alternatively, you can read environment objects that were assigned through your view with the .environmentObject view modifier as follows:

@propertyWrapper
struct UsesEnvironmentObject<T: ObservableObject>: DynamicProperty {
    @EnvironmentObject var envObject: T

    // ...
}

We can use the environment to conveniently pass dependencies to our property wrappers. For example, let’s say you’re building a property wrapper that fetches data from the network. You might have an object named Networking that can perform network calls to fetch the data you need. You could inject this object into the property wrapper through the environment:

@propertyWrapper
struct FeedLoader<Feed: FeedType>: DynamicProperty {
    @Environment(\.network) var network

    var wrappedValue: [Feed.ObjectType] = []
}

The network environment key is a custom key that I’ve added to my SwiftUI environment. To learn more about adding custom values to the SwiftUI environment, take a look at this tip I posted earlier.

Now that we have this property wrapper defined, we need a way to fetch data from the network and assign it to something in order to update our wrapped value. To do this, we can implement the update method that allows us to update data that’s referenced by our property wrapper if needed.

Implementing the update method for your property wrapper

The update method that’s part of the DynamicProperty protocol allows you to respond to SwiftUI’s body evaluations. Whenever SwiftUI is about to evaluate a view’s body, it will call your dynamic property’s update method.

💡 To learn more about how and when SwiftUI evaluates your view’s body, take a look at this post where I explore body evaluation in depth.

As mentioned earlier, you won’t often have a need to implement the update method. I’ve personally found this method to be handy whenever I needed to kick off some kind of data fetching operation. For example, to fetch data from Core Data in a custom implementation of @FetchRequest, or to experiment with fetching data from a server. Let’s expand the FeedLoader property wrapper from earlier a bit to see what a data loading property wrapper might look like:

@propertyWrapper
struct FeedLoader<Feed: FeedType>: DynamicProperty {
    @Environment(\.network) var network
    @State private var feed: [Feed.ObjectType] = []
    private let feedType: Feed
    @State var isLoading = false

    var wrappedValue: [Feed.ObjectType] {
        return feed
    }

    init(feedType: Feed) {
        self.feedType = feedType
    }

    func update() {
        Task {
            if feed.isEmpty && !isLoading {
                self.isLoading = true
                self.feed = try await network.load(feedType.endpoint)
                self.isLoading = false
            }
        }
    }
}

This is a very, very simple implementation of a property wrapper that uses the update method to go to the network, load some data, and assign it to the feed property. We have to make sure that we only load data if we’re not already loading, and we also need to check whether or not the feed is currently empty to avoid loading the same data every time SwiftUI decides to re-evaluate our view’s body.

This of course begs the question, should you use a custom property wrapper to load data from the network? And the answer is, I’m not sure. I’m still heavily experimenting with the update method, its limitations, and its benefits. One thing that’s important to realize is that update is called every time SwiftUI is about to evaluate a view’s body. So synchronously assigning a new value to an @State property from within that method is probably not the best idea; Xcode even shows a runtime warning when I do this.

At this point I’m fairly sure Apple intended update to be used for updating or reading state external to the property wrapper rather than it being used to synchronously update state that’s internal to the property wrapper.

On the other hand, I’m positive that @FetchRequest makes heavy use of update to refetch data whenever its predicate or sort descriptors have changed, probably in a somewhat similar way that I’m fetching data from the network here.

Summary

Writing custom property wrappers for your SwiftUI views is a fun exercise and it’s possible to write some very convenient little helpers to improve your experience while writing SwiftUI views. The fact that your dynamic properties are connected to the SwiftUI view lifecycle and environment is super convenient because it allows you to trigger view updates, and read values from SwiftUI’s environment.

That said, documentation on some of the details surrounding DynamicProperty is severely lacking which means that we can only guess how mechanisms like update() are supposed to be leverages, and why structs work perfectly fine as dynamic properties but classes don’t.

These are some points that I hope to be able to expand on in the future, but for now, there are definitely still some mysteries for me to unravel. And this is where you come in! If you have any additions for this posts, or if you have a solid understanding of how update() was meant to be used, feel free to send me a Tweet. I’d love to hear from you.

Adding custom keys to the SwiftUI environment

Sometimes you’ll find yourself in a situation where you want to conveniently pass some object down via the SwiftUI environment. An easy way to do this is through the .environmentObject view modifier. The one downside of this view modifier and corresponding @EnvironmentObject property wrapper is that the object you add to the environment must be an observable object.

Luckily, we can extend the SwiftUI environment to add our own objects to the @Environment property wrapper without the need to make these objects observable.

For example, your app might have to do some date formatting, and maybe you’re looking for a convenient way to pass a default date formatter around to your views without explicitly passing this date formatter around all the time. The SwiftUI environment is a convenient way to achieve this.

To add our date formatter to the environment, we need to define an EnvironmentKey, and we need to add a computed property to the EnvironmentValues object. Here’s what this looks like:

private struct DateFormatterKey: EnvironmentKey {
    static let defaultValue: DateFormatter = {
        let formatter = DateFormatter()
        formatter.locale = Locale(identifier: "en_US_POSIX")
        formatter.dateFormat = "MM/dd/yyyy"
        return formatter
    }()
}

extension EnvironmentValues {
    var dateFormatter: DateFormatter {
        get { self[DateFormatterKey.self] }
        set { self[DateFormatterKey.self] = newValue }
    }
}

This code conveniently sets up a default date formatter (which is required by the EnvironmentKey protocol). I’ve also added a computed property to EnvironmentValues to make the date formatter object available in my SwiftUI views.

Using this custom environment value is done as follows:

struct LabelView: View {
    @Environment(\.dateFormatter) var dateFormatter
    @State var date: Date

    var body: some View {
        Text("date: \(dateFormatter.string(from: date))")
    }
}

Adding your own keys to the SwiftUI environment can be done for all kinds of reasons. You can use the environment for small objects like the date formatter in this example. But you can even use the environment to pass around more complex objects. For example, you could pass your networking stack around through the SwiftUI environment if this suits your needs.

Hopefully this quick tip is useful for you! I’d love to hear about the kind of things you’re using the SwiftUI environment for in your apps, so make sure to shoot me a Tweet if you’d like to tell me about your experiences.

Five things iOS developers should focus on in 2022

A new year has started and most of us are probably figuring out what we should focus on this year. Whether it’s learning new things or expanding our knowledge on topics we’ve already learned about in the past, there’s always something that deserves our attention in the world of iOS development.

In this short post I’ve listed five things that I believe will help you become a better developer in 2022. Or rather, the first half of 2022. I’m fully expecting Apple to release some cool new interesting things at this year’s WWDC that deserve some of your attention in the second half of the year.

That said, if you focus on the five things listed in this post I’m sure you’ll come out as a stronger developer by the end of the year.

Please not that this list should not be treated as the “definitive” guide to becoming a good developer in 2022. Nor is it a list of the most important topics for everybody that does iOS development.

It’s a list of topics that I believe to be important, and it’s a list of topics that will take up a lot of my time this year. If you disagree with this list, that’s absolutely okay; your priorities do not have to align with mine.

With that out of the way, let’s jump into the first topic on my list.

1. Using SwiftUI alongside UIKit (and vice versa)

One of the most polarising questions I’ve seen in 2021 is probably whether or not SwiftUI is “production ready”. In my opinion that question is way too vague because the answer depends on what an individual’s definition of production ready is within their context. What’s more important in my opinion is the fact that SwiftUI can be used in your apps just fine. Whether you want to go all-in or not, that you’re choice. There are even cases where going all-in on SwiftUI isn’t quite possible for various reasons.

The vast majority of apps I’ve seen and worked on in the past year can get really far with just plain SwiftUI but almost always there are some edges where dropping down to UIKit was needed. Alternatively, I’ve seen existing production apps that wanted to start integrating SwiftUI without rewriting everything straight away which is completely reasonable.

Luckily, we can use SwiftUI and UIKit simultaneously in our projects and I would highly encourage folks to do this. Make sure you dig and understand how to mix SwiftUI into a UIKit app, or how you can fall back to UIKit in a SwiftUI app if you find that you’re running into limitations with purely using SwiftUI.

Knowing how to do this will allow you to adopt SwiftUI features where possible, and speed up your development process because writing UI with SwiftUI is so much faster than UIKit (when it suits your needs). On top of that, it will take a while for companies to have all their apps written exclusively in SwiftUI so knowing how to gradually introduce it is a really valuable skill to have as an employee or even as someone who’s looking for their next (or their first) job.

2. App Architecture

No, I don’t mean “learn VIPER” or “learn all the architectures”. In fact, I’m not saying you should learn any app architecture in particular.

In my opinion it’s far more valuable to understand the principles that virtually every architecture is built upon; separation of concerns. Knowing how and when to split your app’s functionality into different components, and knowing how these components should be structured is extremely important when you want to write code that’s easy to reason about, easy to refactor, and easy to test.

Try and learn about topics such as single responsibility principle, dependency injection, abstractions, protocols, generics, and more. Once you’ve learned about these topics, you’ll find a lot of the architectural patterns out there are just different applications of the same principles. In other words, lots of architectures provide a framework for you and your team to reason about different layers in your codebase rather that a completely unique way of working.

A less obvious reason to learn more about app architecture is that it will help you write code that can work in a SwiftUI world as well as a UIKit world which is extremely useful given what I explained in the first point on this list. The ability to architect a codebase that works with both SwiftUI and UIKit is extremely useful and will definitely help you enjoy the experience of mixing UI frameworks more.

3. Async-Await

If there’s one topic that I just couldn’t leave off this list it’s async-await. Or rather, Swift’s new concurrency model. With the introduction of async-await Apple didn’t just introduce some syntactic sugar (like how async-await is essentially sugar over promises in JavaScript). Apple introduce a whole new modern concurrency system that we can leverage in our apps.

Topics like structured concurrency, actors, task groups, and more are extremely useful to learn about this year. Especially because Apple’s managed to backport Swift Concurrency all the way to iOS 13. Make sure you’re using Xcode 13.2 or newer if you want to use Swift Concurrency in apps that target iOS 13.0 and up, and you should be good to go.

If you want to learn more about Swift Concurrency, I have a couple posts available on my blog already. Click here to go to the Swift Concurrency category.

4. Core Data

Yes. It’s a pretty old framework and its Objective-C roots are not very well hidden. Regardless, Apple’s clearly still interested in having people use and adopt Core Data given the fact that they’ve added new features for Core Data + SwiftUI in iOS 15, and previous iOS versions received various Core Data updates too.

Will Apple replace Core Data with a more Swift-friendly alternative soon? I honestly don’t know. I don’t think it’s likely that Apple will do a complete replacement any time soon. It seems more likely for Apple to keep Core Data’s core bits and provide us a more Swift-friendly API on top of this. That way the transition from the current API to a newer API can be done step by step, and our apps won’t have to go through some major migration if we want to leverage the latest and greatest. Pretty similar to how Apple is introducing SwiftUI.

Is Core Data the absolute best way to persist data in all cases? Probably not. Is it extremely difficult to implement and way too heavy for most apps? No, not at all. Core Data really isn’t that scary, and it integrates with SwiftUI really nicely. Check out this video I did on using Core Data in a SwiftUI application for example.

If you want to learn more about Core Data this year, I highly recommend you pick up my Practical Core Data book. It teaches you everything you need to know to make use of Core Data effectively in both SwiftUI and UIKit applications.

5. Accessibility

Last but by no means least on my list is a topic that I myself should learn more about. Accessibility is often considered optional, a “feature”, or something you do last in your development process. Or honestly, it’s not even rare for accessibility to not be considered on a roadmap at all.

When you think of accessibility like that, there’s a good chance your app isn’t accessible at all because you never ended up doing the work. I’m not entirely sure where I’ve heard this first but if you’re not sure whether your app is accessible or not, it isn’t.

Accessibility is something we should actively keep an eye on to make sure everybody can use our apps. Apple’s tools for implementing and testing accessibility are really good, and I have to admit I know far too little about them. So for 2022, accessibility is absolutely on my list of things to focus on.

Forcing an app out of memory on iOS

I’ve recently been working on a background uploading feature for an app. One of the key aspects to get right with a feature like that is to correctly handle scenarios where your app is suspended by the system due to RAM constraints or other, similar, reasons. Testing this is easily done by clearing the RAM memory on your device. Unfortunately, this isn’t straightforward. But it’s also not impossible.

Note that opening the task switcher and force closing your app from there is not quite the same as forcing your app to be suspended. Or rather, it’s not the same as forcing your app out of memory.

Luckily, there’s somewhat of a hidden trick to clear your iOS device’s RAM memory, resulting in your app getting suspended just like it would if the device ran out of memory due to something your user is doing.

To force-clear your iOS device’s RAM memory, go through the following steps:

  1. If you’re using a device without a home button, enable Assistive Touch. If your device has a home button you can skip this step. You can enable Assistive Touch by going to Settings → Accessibility → Touch → Enable Assistive Touch. This will make a floating software button appear on your device that can be tapped to access several shortcuts, a virtual home button is one of these shortcuts.

Settings window for accessibility -> touch -> assistive touch

  1. In a (somewhat) fluid sequence press volume up, volume down, and then hold your device’s power button until a screen appears that allows you to power down your device.
  2. Once that screen appears, tap the assistive touch button and then press and hold the virtual home button until you’re prompted to unlock your device. You’ve successfully wiped your device’s RAM memory.

Shut down screen with assistive touch actions visible

Being able to simulate situations where your app goes out of memory is incredibly useful when you’re working on features that rely on your app being resumed in the background even when it’s out of memory. Background uploads and downloads are just some examples of when this trick is useful.

My favorite part of using this approach to debug my apps going out of memory is that I can do it completely detached from Xcode, and I can even ask other people like a Q&A department to test with this method to ensure everything works as expected.

An app that's forced out of ram is not considered closed because it's still present in the app switcher, and any background processes continue to run. during normal device usage, apps will be forced out of ram whenever ann app that the user is using needs more ram, of if a user hasn't opened your app in a while. When the user launches your app the app will still boot as a fresh launch with the main difference being that the app might have done work in the background.

When an app is force closed from the app switcher, iOS does not allow this app to continue work in the background, so any in progress uploads or other tasks are considered cancelled.

Understanding how and when SwiftUI decides to redraw views

There's a good chance that you're using SwiftUI and that you're not quite sure how and when SwiftUI determines which views should redraw. And arguably, that's a good thing. SwiftUI is clearly smart enough to make decent decisions without any negative consequences. In fact, you might even have set up your app in a way that coincidentally plays into SwiftUI's strength beautifully. There's an equal likelihood that your setup isn't as performant as you might think but you're just not seeing any issues yet.

Recently, I had to figure out how SwiftUI determines that it should redraw views in order to fix some performance issues. One issue was that for some reason SwiftUI decided that it needed access the bodies of a lot of views that never changed which led to some dropped frames while scrolling. Another issue that I investigated is one where scrolling performance suffered greatly when just one or two items in a list were updated.

The details and specifics of these issues aren't that interesting. What's more interesting in my opinion is what I learned about how and when SwiftUI determines to redraw views because some of the things I've noticed were quite surprising to me while others felt very natural and confirmed some thoughts I've had regarding SwiftUI for a while.

Please keep in mind that I don't have insight into SwiftUI's internals, the information I've gathered in this post is based on observations and measurements and there are no guarantees that they'll remain accurate in the future. In general you shouldn't rely on undocumented internals, even if you have lots of proof to back up your reasoning. That said, the measurements in this post were done to solve real problems, and I think the conclusions that can be drawn from these measurements explain sensible best-practices without relying on the internals of SwiftUI too much.

With that out of the way, let's dive right in!

Understanding the example we'll work from

The most important thing to understand while we're exploring SwiftUI is the example that I'm using to work from. Luckily, this example is relatively simple. If you want to check out the source code that I've used to gather measurements during my exploration, you can grab it from GitHub.

The sample I've been working from is based on a list of items. There's functionality to set a list item to "active". Doing this will mark the currently active item (if one exists) as not active, and the next item in the list becomes active. I can either do this by hand, or I can do it on a timer. The models used to populate my cells also have a random UUID that's not shown in the cell. However, when changing the active cell there's an option in the app to update the random UUID on every model in the my data source.

I'll show you the important parts of my model and data source code first. After that I'll show you the view code I'm working from, and then we can get busy with taking some measurements.

Understanding the sample's data model

My sample app uses an MVVM-like strategy where cells in my list receive a model object that they display. The list itself uses a view model that maintains some state surrounding which item is active, and whether a list of items is loaded already.

Let's look at the model that's shown in my cells first:

struct Item: Identifiable {
    var isActive: Bool
    let id = UUID()
    var nonVisibleProperty = UUID()

    init(id: UUID = UUID(), isActive: Bool = false, nonVisibleProperty: UUID = UUID()) {
        self.isActive = isActive
    }
}

It's pretty simple and what's important for you to note is that my model is a struct. This means that changing the nonVisibleProperty or isActive state does not trigger a view redraw. The reason for this is that there's a view model that holds all of the items I want to show. The view model is an observable object and whenever one of its items changes, it will update its @Published list of items.

I won't put the full view model code in this post, you can view it right here on GitHub if you're interested to see the entire setup.

The list of items is defined as follows:

@Published var state: State = .loading

By using a State enum it's possible to easily show appropriate UI that corresponds to the state of the view model. For simplicity I only have two states in my State enum:

enum State {
    case loading
    case loaded([Item])
}

Probably the most interesting part of the view model I defined is how I'm toggling my model's isActive property. Here's what my implementation looks like for the method that activates the next item in my list:

func activateNextItem() {
    guard case .loaded(let items) = state else {
        return
    }

    var itemsCopy = items

    defer {
        if isMutatingHiddenProperty {
            itemsCopy = itemsCopy.map { item in
                var copy = item
                copy.nonVisibleProperty = UUID()
                return copy
            }
        }

        self.state = .loaded(itemsCopy)
    }

    guard let oldIndex = activeIndex, oldIndex + 1 < items.endIndex else {
        activeIndex = 0
        setActiveStateForItem(at: activeIndex!, to: true, in: &itemsCopy)
        return
    }

    activeIndex = oldIndex + 1

    setActiveStateForItem(at: oldIndex, to: false, in: &itemsCopy)
    setActiveStateForItem(at: activeIndex!, to: true, in: &itemsCopy)
}

I'm using a defer to assign a copy of my list of items to self.state regardless of whether my guard requirement is satisfied or not.

If this method looks suboptimal to you, that's ok. The point of this exercise was never to write optimal code. The point is to write code that allows us to observe and analyze SwiftUI's behavior when it comes to determining to which views get redrawn and when.

Before we start taking some measurements, I want to show you what my views look like.

Understanding the sample's views

The sample views are quite simple so I won't explain them in detail. My cell view looks as follows:

struct StateDrivenCell: View {
    let item: Item

    var body: some View {
        VStack(alignment: .leading, spacing: 8) {
            HStack {
                VStack(alignment: .leading) {
                    Text("identifier:").bold()
                    Text(item.id.uuidString.split(separator: "-").first!)
                }
                Spacer()
            }

            HStack {
                VStack(alignment: .leading) {
                    Text("active state:").bold()
                    Text("is active: \(item.isActive  ? "✅ yes": "❌ no")")
                }
                Spacer()
            }

        }.padding()
    }
}

All this cell does is display its model. Nothing more, nothing less.

The list view looks as follows:

struct StateDrivenView: View {
    @StateObject var state = DataSource()

    var body: some View {
        NavigationView {
            ScrollView {
                if case .loaded(let items) = state.state {
                    LazyVStack {
                        ForEach(items) { item in
                            StateDrivenCell(item: item)
                        }
                    }
                } else {
                    ProgressView()
                }
            }
            .toolbar {
                // some buttons to activate next item, start timer, etc.
            }
            .navigationTitle(Text("State driven"))
        }
        .onAppear {
            state.loadItems()
        }
    }
}

Overall, this view shouldn't surprise you too much.

When looking at this, you might expect things to be suboptimal and you would maybe set this example up in a different way. That's okay because again, the point of this code is not to be optimal. In fact, as our measurements will soon prove, we can write much better code with minimal changes. Instead, the point is to observe and analyze how SwiftUI determines what it should redraw.

To do that, we'll make extensive use of Instruments.

Using Instruments to understand SwiftUI's redraw behavior

When we run our app, everything looks fine at first glance. When we set the application up to automatically update the active item status every second, we don't see any issues. Even when we set the application up to automatically mutate our non-visible property everything seems completely fine.

At this point, it's a good idea to run the application with the SwiftUI Instruments template to see if everything looks exactly as we expect.

In particular, we're looking for body access where we don't expect it.

If everything works correctly, we only want the view bodies for cells that have different data to be accessed. More specifically, ideally we don't redraw any views that won't end up looking any different if they would be redrawn.

Whenever you build your app for profiling in Xcode, Instruments will automatically open. If you're running your own SwiftUI related profiling, you'll want to select the SwiftUI template from Instruments' templates.

Instruments' template selection screen

Once you've opened the SwiftUI template, you can run your application and perform the interactions that you want to profile. In my case, I set my sample app up to automatically update the active item every second, and every time this happens I change some non-visible properties to see if cells are redrawn even if their output looks the same.

When I run the app with this configuration, here's what a single timer tick looks like in Instruments when I focus on the View Body timeline:

A screenshot of Instruments that shows 6 cells get re-evaluated

In this image, you can see that the view body for StateDrivenCell was invoked six times. In other words, six cells got their bodies evaluated so they could be redrawn on the screen. This number is roughly equal to the number of cells on screen (my device fits five cells) so to some extent this makes sense.

On the other hand, we know that out of these six cells only two actually updated. One would have its isActive state flipped from true to false and the other would have its isActive state flipped from false to true. The other property that we updated is not shown and doesn't influence the cell's body in any way. If I run the same experiment except I don't update the non-visible property every time, the result is that only two cell bodies get re-evaluated.

Instruments screenshot that shows 2 cells get re-evaluated when we don't change a non-visible property

We can see that apparently SwiftUI is smart enough to somehow compare our models even though they're not Equatable. In an ideal world, we would write our app in a way that would ensure only the two cell bodies that show the models that changed in a meaningful way are evaluated.

Before we dig into that, take a good look at what's shown in Instruments. It shows that StateDrivenView also has its body evaluated.

The reason this happens is that the StateDrivenView holds a @StateObject as the source of truth for the entire list. Whenever we change one of the @StateObject's published properties, the StateDrivenView's body will be evaluated because its source of truth changed.

Note that body evalulation is not guaranteed to trigger an actual redraw on the screen. We're seeing Core Animation commits in the Instruments anlysis so it's pretty safe to assume something got redrawn, but it's hard to determine what exactly. What's certain though is that if SwiftUI evaluates the body of a view, there's a good chance this leads to a redraw of the accessed view itself, or that one of its child views needs to be redrawn. It's also good to mention that a body evaluation does not immediately lead to a redraw. In other words, if a view's body is evaulated multiple times during a single render loop, the view is only redrawn once. As a mental model, you can think of SwiftUI collecting views that need to be redrawn during each render loop, and then only redrawing everything that needs to be redrawn once rather than commiting a redraw for every change (this would be wildly inefficient as you can imagine). This model isn't 100% accurate, but in my opinion it's good enough for the context of this blog post.

Because we're using a LazyVStack in the view, not all cells are instantiated immediately which means that the StateDrivenView will initially only create about six cells. Each of these six cells gets created when the StateDrivenView's body is re-evaluated and all of their bodies get re-evaluated too.

You might think that this is just the way SwiftUI works, but we can actually observe some interesting behavior if we make some minor changes to our model. By making our model Equatable, we can give some hints to SwiftUI about whether or not the underlying data for our cell got changed. This will in turn influence whether the cell's body is evaluated or not.

This is also where things get a little... strange. For now, let's pretend everything is completely normal and add an Equatable conformance to our model to see what happens.

Here's what my conformance looks like:

struct Item: Identifiable, Equatable {
    var isActive: Bool
    let id = UUID()
    var nonVisibleProperty = UUID()

    init(id: UUID = UUID(), isActive: Bool = false, nonVisibleProperty: UUID = UUID()) {
        self.isActive = isActive
    }

    static func == (lhs: Item, rhs: Item) -> Bool {
        return lhs.id == rhs.id && lhs.isActive == rhs.isActive
    }
}

The parameters for my test are the exact same. Every second, a new item is made active, the previously active item is made inactive. The nonVisibleProperty for every item in my list is mutated.

My Equatable conformance ignores the nonVisibleProperty and only compares the id and the isActive property. Based on this, what I want to happen is that only the bodies of the cells who's item's isActive state changed is evaluated.

Unfortunately, my Instruments output at this point still looks the same.

A screenshot of Instruments that shows 6 cells get re-evaluated

While I was putting together the sample app for this post, this outcome had me stumped. I literally had a project open alongside this project where I could reliably fix this body evaluation by making my model Equatable. After spending a lot of time trying to figure out what was causing this, I added a random String to my model, making it look like this:

struct Item: Identifiable, Equatable {
    var isActive: Bool
    let id = UUID()
    var nonVisibleProperty = UUID()
    let someString: String

    init(id: UUID = UUID(), isActive: Bool = false, nonVisibleProperty: UUID = UUID()) {
        self.isActive = isActive
        self.someString = nonVisibleProperty.uuidString
    }

    static func == (lhs: Item, rhs: Item) -> Bool {
        return lhs.id == rhs.id && lhs.isActive == rhs.isActive
    }
}

After updating the app with this random String added to my model, I'm suddenly seeing the output I was looking for. The View body timeline now shows that only two StateDrivenCell bodies get evaluated every time my experiment runs.

A screenshot of Instruments that shows 2 cells get re-evaluated with our updates in place

It appears that SwiftUI determines whether a struct is a plain data type, or a more complex one by running the built-in _isPOD function that's used to determin whether a struct is a "plain old data" type. If it is, SwiftUI will use reflection to directly compare fields on the struct. If we're not dealing with a plain old data type, the custom == function is used. Adding a String property to our struct changes it from being a plain old data type to a complex type which means SwiftUI will use our custom == implementation.

To learn more about this, take a look at this post by the SwiftUI Lab.

After I realized that I can make my models conform to Equatable and that influences whether my view's body is evaluated or not, I was wondering what leads SwiftUI to compare my model struct in the first place. After all, my cell is defined is follows:

struct StateDrivenCell: View {
    let item: Item

    var body: some View {
        VStack(alignment: .leading, spacing: 8) {
            // cell contents
        }.padding()
    }
}

The item property is not observed. It's a simple stored property on my view. And according to Instruments my view's body isn't evaluated. So it's not like SwiftUI is comparing the entire view. More interestingly, it was able to do some kind of comparison before I made my model Equatable.

The only conclusion that I can draw here is that SwiftUI will compare your models regardless of their Equatable conformance in order to determine whether a view needs to have its body re-evaluated. And in some cases, your Equatable conformance might be ignored.

At this point I was curious. Does SwiftUI evaluate everything on my struct that's not my body? Or does it evaluate stored properties only? To find out, I added the following computed property to my view:

var randomInt: Int { Int.random(in: 0..<Int.max) }

Every time this is accessed, it will return a new random value. If SwiftUI takes this property into account when it determines whether or not StateDrivenCell's body needs to be re-evaluated, that means that this would negate my Equatable conformance.

After profiling this change with Instruments, I noticed that this did not impact my body access. The body for only two cells got evaluated every second.

Then I redefined randomInt as follows:

let randomInt = Int.random(in: 0..<Int.max)

Now, every time an instance of my struct is created, randomInt will get a constant value. When I ran my app again, I noticed that I was right back where I started. Six body evaluations for every time my experiment runs.

A screenshot of Instruments that shows 6 cells get re-evaluated

This led me to conclude that SwiftUI will always attempt to compare all of its stored properties regardless of whether they're Equatable. If you provide an Equatable conformance on one of the view's stored properties this implementation will be used if SwiftUI considers it relevant for your model. It's not quite clear when using your model's Equatable implementation is or is not relevant according to SwiftUI.

An interesting side-note here is that it's also possible to make your view itself conform to Equatable and compare relevant model properties in there if the model itself isn't Equatable:

extension StateDrivenCell: Equatable {
    static func ==(lhs: StateDrivenCell, rhs: StateDrivenCell) -> Bool {
        return lhs.item.id == rhs.item.id && lhs.item.isActive == rhs.item.isActive
    }
}

What's interesting is that this conformance is pretty much ignored under the same circumstances as before. If Item does not have this extra string that I added, there are six cell bodies accessed every second. Adding the string back makes this work properly regardless of whether the Item itself is Equatable.

I told you things would get weird here, didn't I...

Overall, I feel like the simple model I had is probably way too simple which might lead SwiftUI to get more eager with its body access. The situation where an Equatable conformance to a model would lead to SwiftUI no longer re-evaluating a cell's body if the model is considered equal seems more likely in the real world than the situation where it doesn't.

In fact, I have tinkered with this in a real app, a sample experiment, and a dedicated sample app for this post and only in the dedicated app did I see this problem.

Takeaways on SwiftUI redrawing based on Instruments analysis

What we've seen so far is that SwiftUI will evaluate a view's body if it thinks that this view's underlying data will change its visual representation (or that of one the view's subviews). It will do so by comparing all stored properties before evaluating the body, regardless of whether these stored properties are Equatable.

If your stored properties are Equatable, SwiftUI might decide to rely on your Equatable conformance to determine whether or not your model changed. If SwiftUI determines that all stored properties are still equal, your view's body is not evaluated. If one of the properties changed, the body is evaluated and each of the views returned from your view's body is evaluated in the same way that I just described.

Conforming your view to Equatable works in the same way except you get to decide which properties participate in the comparison. This means that you could take computed properties into account, or you could ignore some of your view's stored properties.

Note that this only applies to view updates that weren't triggered by a view's @ObservedObject, @StateObject, @State, @Binding, and similar properties. Changes in these properties will immediately cause your view's body to be evaluated.

Designing your app to play into SwiftUI's behavior

Now that we know about some of SwiftUI's behavior, we can think about how our app can play into this behavior. One thing I've purposefully ignored up until now is that the body for our StateDrivenView got evaluated every second.

The reason this happens is that we assign to the DataSource's state property every second and this property is marked with @Published.

Technically, our data source didn't really change. It's just one of the properties on one of the models that we're showing in the list that got changed. It'd be far nicer if we could scope our view updates entirely to the cells holding onto the changed models.

Not only would this get rid of the StateDrivenView's body being evaluated every second, it would allow us to get rid of the entire Equatable conformance that we added in the previous section.

To achieve this, we can keep the @Published property on DataSource. It doesn't need to be changed. What needs to be updated is the definition of Item, and the way we toggle the active item.

First, let's make Item a class and mark it as an ObservableObject. We'll also mark its isActive property as @Published:

class Item: Identifiable, ObservableObject {
    @Published var isActive: Bool
    let id = UUID()
    var nonVisibleProperty = UUID()

    init(id: UUID = UUID(), isActive: Bool = false, nonVisibleProperty: UUID = UUID()) {
        self.isActive = isActive
    }
}

Note that I got rid of someString since its only purpose was to make the Equatable workaround work.

The view needs to be updated to use Item as an observed object:

struct StateDrivenView: View {
    @ObservedObject var item: Item

    var body: some View {
        VStack(alignment: .leading, spacing: 8) {
            HStack {
                VStack(alignment: .leading) {
                    Text("identifier:").bold()
                    Text(item.id.uuidString.split(separator: "-").first!)
                }
                Spacer()
            }

            HStack {
                VStack(alignment: .leading) {
                    Text("active state:").bold()
                    Text("is active: \(item.isActive ? "✅ yes": "❌ no")")
                }
                Spacer()
            }

        }.padding()
    }
}

Now that Item can be observed by our view, we need to change the implementation of activateNextItem() in the DataSource:

func activateNextItem() {
    guard case .loaded(let items) = state else {
        return
    }

    defer {
        if isMutatingHiddenProperty {
            for item in items {
                item.nonVisibleProperty = UUID()
            }
        }
    }

    guard let oldIndex = activeIndex, oldIndex + 1 < items.endIndex else {
        activeIndex = 0
        items[activeIndex!].isActive = true
        return
    }

    activeIndex = oldIndex + 1

    items[oldIndex].isActive = false
    items[activeIndex!].isActive = true
}

Instead of updating the state property on DataSource every time this method is called, I just mutate the items I want to mutate directly.

Running the sample app with Instruments again yields the following result:

A screenshot of Instruments that shows 2 cells get re-evaluated and the list itself is not evaluated

As you can see, only two cell bodies get evaluated now. That's the cell that's no longer active, and the newly activated cell. The StateDrivenView itself is no longer evaluated every second.

I'm sure you can imagine that this is the desired situation to be in. We don't want to re-evaluate and redraw our entire list when all we really want to do is re-evaluate one or two cells.

The lesson to draw from this optimization section is that you should always aim to make your data source scope as small as possible. Triggering view updates from way up high in your view hierarchy to update something that's all that way at the bottom is not very efficient because all of the bodies of views in between will need to be evaluated and redrawn in the process.

Conclusions

In this post you learned a lot about how and when SwiftUI decides to redraw your views. You learned that if the model for a view contains properties that changed, SwiftUI will re-evaluate the view's body. This is true even if the changed properties aren't used in your view. More interestingly, you saw that SwiftUI can compare your models even if they're not Equatable.

Next, I showed you that adding Equatable conformance to your model can influence how SwiftUI decides whether or not your view's body needs to be re-evaluated. There's one caveat though. Your Equatable conformance won't influence SwiftUI's re-evaluation behavior depending on whether your model object is a "plain old data" object or not.

After that, you saw that your view will automatically take all of its stored properties into account when it decides whether or not your view's body needs re-evaluation. Computed properties are ignored. You also saw that instead of conforming your model to Equatable, you can conform your views to Equatable and as far as I can tell, the same caveat mentioned earlier applies.

Lastly, you saw that in order to keep tight control over your views and when they get redrawn, it's best to keep your data sources small and focussed. Instead of having a global state that contains a lot of structs, it might be better have your models as ObservableObjects that can be observed at a more granular level. This can, for example, prevent your lists body from being evaluated and works around the extra redraws that were covered in the first half of this post entirely.

I'd like to stress one last time that it's not guaranteed that SwiftUI will continue working the way it does, and this post is an exercise in trying to unravel some of SwiftUI's mysteries like, for example, how SwiftUI's diffing works. Investigating all of this was a lot of fun and if you have any additions, corrections, or suggestions for this post I'd love to add them, please send them to me on Twitter.

Understanding Swift’s AsyncSequence

The biggest features in Swift 5.5 all revolve around its new and improved concurrency features. There's actors, async/await, and more. With these features folks are wondering whether async/await will replace Combine eventually.

While I overall do not think that async/await can or will replace Combine on its own, Swift 5.5 comes with some concurrency features that provide very similar functionality to Combine.

If you're curious about my thoughts on Combine and async/await specifically, I still believe that what I wrote about this topic earlier is true. Async/await will be a great tool for work that have a clearly defined start and end with a single output while Combine is more useful for observing state and responding to this state.

In this post, I would like to take a look at a Swift Concurrency feature that provides a very Combine-like functionality because it allows us to asynchronously receive and use values. We'll take a look at how an async sequence is used, and when you might want to choose an async sequence over Combine (and vice versa).

Using an AsyncSequence

The best way to explain how Swift's AsyncSequence works is to show you how it can be used. Luckily, Apple has added a very useful extension to URL that allows us to asynchronously read lines from a URL. This can be incredibly useful when your server might stream data as it becomes available instead of waiting for all data to be ready before it begins sending an HTTP body. Alternatively, your server's response format might allow you to begin parsing and decoding its body line by line. An example of this would be a server that returns a csv file where every line in the file represents a row in the returned dataset.

Iterating over an async sequence like the one provided by URL looks as folllows:

let url = URL(string: "https://www.donnywals.com")!
for try await line in url.lines {
    print(line)
}

This code only works when you're in an asynchronous context, this is no different from any other asynchronous code. The main difference is in how the execution of the code above works.

A simple network call with async/await would look as follows:

let (data, response) = try await URLSession.shared.data(from: url)

The main difference here is that URLSession.shared.data(from:) only returns a single result. This means that the url is loaded asynchronously, and you get the entire response and the HTTP body back at once.

When you iterate over an AsyncSequence like the one provided through URL's lines property, you are potentially awaiting many things. In this case, you await each line that's returned by the server.

In other words, the for loop executes each time a new line, or a new item becomes available.

The example of loading a URL line-by-line is not something you'll encounter often in your own code. However, it could be a useful tool if your server's responses are formatted in a way that would allow you to parse the response one line at a time.

A cool feature of AsyncSequence is that it behaves a lot like a regular Sequence in terms of what you can do with it. For example, you can transform your the items in an AsyncSequence using a map:

let url = URL(string: "https://www.donnywals.com")!
let sequence = url.lines.map { string in
    return string.count
}

for try await line in sequence {
    print(line)
}

Even though this example is very simple and naive, it shows how you can map over an AsyncSequence.

Note that AsyncSequence is not similar to TaskGroup. A TaskGroup runs multiple tasks that each produce a single result. An AsyncSequence on the other hand is more useful to wrap a single task that produces multiple results.

However, if you're familiar with TaskGroup, you'll know that you can obtain the results of the tasks in a group by looping over it. In an earlier post I wrote about TaskGroup, I showed the following example:

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
    }
}

Note how the last couple of likes await each movie in the group. That's because TaskGroup itself conforms to AsyncSequence. This means that we can iterate over the group to obtain results from the group as they become available.

In my post on TaskGroup, I explain how a task that can throw an error can cause all tasks in the group to be cancelled if the error is thrown out of the task group. This means that you can still catch and handle errors inside of your task group to prevent your group from failing. When you're working with AsyncSequence, this is slightly different.

AsyncSequence and errors

Whenever an AsyncSequence throws an error, your for loop will stop iterating and you'll receive no further values. Wrapping the entire loop in a do {} catch {} block doesn't work; that would just prevent the enclosing task from rethrowing the error, but the loop still stops.

This is part of the contract of how AsyncSequence works. A sequence ends either when its iterator returns nil to signal the end of the sequence, or when it throws an error.

Note that a sequence that produces optional values like String? can exist and if a nil value exists this wouldn't end the stream because the iterator would produce an Optional.some(nil). The reason for this is that an item of type String? was found in the sequence (hence Optional.some) and its value was nil. It's only when the iterator doesn't find a value and returns nil (or Optional.none) that the stream actually ends.

In the beginning of this post I mentioned Combine, and how AsyncSequence provides some similar features to what we're used to in Combine. Let's take a closer look at similarities and differences between Combine's publishers and AsyncSequence.

AsyncSequence and Combine

The most obvious similarities between Combine and AsyncSequence are in the fact that both can produce values over time asynchronously. Furthermore, they both allow us to transform values using pure functions like map and flatMap. In other words, we can use functional programming to transform values. When we look at how thrown errors are handled, the similarities do not stop. Both Combine and AsyncSequence end the stream of values whenever an error is thrown.

To sum things up, these are the similarities between Combine and AsyncSequence:

  • Both allow us to asynchronously handle values that are produced over time.
  • Both allow us to manipulate the produced values with functions like map, flatMap, and more.
  • Both end their stream of values when an error occurs.

When you look at this list you might thing that AsyncSequence clearly replaces Combine.

In reality, Combine allows us to easily do things that we can't do with AsyncSequence. For example, we can't debounce values with AsyncSequence. We also can't have one asynchronous iterator that produces values for multiple for loops because iterators are destructive which means that if you loop over the same iterator twice, you should expect to see the second iterator return no values at all.

I'm sure there are ways to work around this but we don't have built-in support at this time.

Furthermore, at this time we can't observe an object's state with an AsyncSequence which, in my opinion is where Combine's value is the biggest. Again, I'm sure you could code up something that leverages KVO to build something that observes state but it's not built-in at this time.

This is most obvious when looking at an ObservableObject that's used with SwiftUI:

class MyViewModel: ObservableObject {
  @Published var currentValue = 0
}

SwiftUI can observe this view model's objectWillChange publisher to be notified of changes to any of the ObservableObject's @Published properties. This is really powerful, and we currently can't do this with AsyncSequence. Furthermore, we can use Combine to take a publisher's output, transform it, and assign it to an @Published property with the assign(to:) operator. If you want to learn more about this, take a look at this post I wrote where I use the assign(to:) operator.

Two other useful features we have in Combine are CurrentValueSubject and PassthroughSubject. While AsyncSequence itself isn't equivalent to Subject in Combine, we can achieve similar functionality with AsyncStream which I plan to write a post about soon.

The last thing I'd like to cover is the lifetime of an iterator versus that of a Combine subscription. When you subscribe to a Combine publisher you are given a cancellable to you must persist to connect the lifetime of your subscription to the owner of the cancellable. To learn more about cancellables in Combine, take a look at my post on AnyCancellable.

You can easily subscribe to a Combine publisher in a regular function in your code:

var cancellables = Set<AnyCancellable>()

func subscribeToPublishers() {
  viewModel.$numberOfLikes.sink { value in 
    // use new value
  }.store(in: &cancellables)

  viewModel.$currentUser.sink { value in 
    // use new value
  }.store(in: &cancellables)
}

The lifetime of these subscriptions is tied to the object that holds my set of cancellables. With AsyncSequence this lifecycle isn't as clear:

var entryTask: Task<Void, Never>?

deinit {
  entryTask.cancel()
}

func subscribeToSequence() {
  entryTask = Task {
    for await entry in viewModel.fetchEntries {
      // use entry
    }
  }
}

We could do something like the above to cancel our sequence when the class that holds our task is deallocated but this seems very error prone, and I don't think its as elegant as Combine's cancellable.

Summary

In this post, you learned about Swift's AsyncSequence and you've learned a little bit about how it can be used in your code. You learned about asynchronous for loops, and you saw that you can transform an AsyncSequence output.

In my opinion, AsyncSequence is a very useful mechanism to obtain values over time from a process that has a beginning and end. For more open ended tasks like observing state on an object, I personally think that Combine is a better solution. At least for now it is, who knows what the future brings.

Using Swift’s async/await to build an image loader

Async/await will be the defacto way of doing asynchronous programming on iOS 15 and above. I've already written quite a bit about the new Swift Concurrency features, and there's still plenty to write about. In this post, I'm going to take a look at building an asynchronous image loader that has support for caching.

SwiftUI on iOS 15 already has a component that allows us to load images from the network but it doesn't support caching (other than what’s already offered by URLSession), and it only works with a URL rather than also accepting a URLRequest. The component will be fine for most of our use cases, but as an exercise, I'd like to explore what it takes to implement such a component ourselves. More specifically I’d like to explore what it’s like to build an image loader with Swift Concurrency.

We'll start by building the image loader object itself. After that, I'll show how you can build a simple SwiftUI view that uses the image loader to load images from the network (or a local cache if possible). We'll make it so that the loader work with both URL and URLRequest to allow for maximum configurability.

Note that the point of this post is not to show you a perfect image caching solution. The point is to demonstrate how you'd build an ImageLoader object that will check whether an image is available locally and only uses the network if the requested image isn't available locally.

Designing the image loader API

The public API for our image loader will be pretty simple. It'll be just two methods:

  1. public func fetch(_ url: URL) async throws -> UIImage
  2. public func fetch(_ urlRequest: URLRequest) async throws -> UIImage

The image loader will keep track of in-flight requests and already loaded images. It'll reuse the image or the task that's loading the image whenever possible. For this reason, we'll want to make the image loader an actor. If you're not familiar with actors, take a look at this post I published to brush up on Swift Concurrency's actors.

While the public API is relatively simple, tracking in-progress fetches and loading images from disk when possible will require a little bit more effort.

Defining the ImageLoader actor

We'll work our way towards a fully featured loader one step at a time. Let's start by defining the skeleton for the ImageLoader actor and take it from there.

actor ImageLoader {
    private var images: [URLRequest: LoaderStatus] = [:]

    public func fetch(_ url: URL) async throws -> UIImage {
        let request = URLRequest(url: url)
        return try await fetch(request)
    }

    public func fetch(_ urlRequest: URLRequest) async throws -> UIImage {
        // fetch image by URLRequest
    }

    private enum LoaderStatus {
        case inProgress(Task<UIImage, Error>)
        case fetched(UIImage)
    }
}

In this code snippet I actually did a little bit more than just define a skeleton. For example, I've defined a private enum LoaderStatus. This enum will be used to keep track of which images we're loading from the network, and which images are available immediately from memory. I also went ahead and implemented the fetch(:) method that takes a URL. To keep things simple, it just constructs a URLRequest with no additional configuration and calls the overload for fetch(_:) that takes a URLRequest.

Now that we have a skeleton ready to go, we can start implementing the fetch(_:) method. There are essentially three different scenarios that we can run into. Interestingly enough, these three scenarios are quite similar to what I wrote in an earlier Swift Concurrency related post that covered refreshing authentication tokens.

The scenarios can be roughly defined as follows:

  1. fetch(_:) has already been called for this URLRequest so will either return a task or the loaded image.
  2. We can load the image from disk and store it in-memory
  3. We need to load the image from the network and store it in-memory and on disk

I'll show you the implementation for fetch(_:) one step at a time. Note that the code won't compile until we've finished the implementation.

First, we'll want to check the images dictionary to see if we can reuse an existing task or grab the image directly from the dictionary:

public func fetch(_ urlRequest: URLRequest) async throws -> UIImage {
    if let status = images[urlRequest] {
        switch status {
        case .fetched(let image):
            return image
        case .inProgress(let task):
            return try await task.value
        }
    }

    // we'll need to implement a bit more before this code compiles
}

The code above shouldn't look too surprising. We can simply check the dictionary like we would normally. Since ImageLoader is an actor, it will ensure that accessing this dictionary is done in a thread safe way (don't forget to refer back to my post on actors if you're not familiar with them yet).

If we find an image, we return it. If we encounter an in-progress task, we await the task's value to obtain the requested image without creating a new (duplicate) task.

The next step is to check whether the image exist on disk to avoid having to go to the network if we don't have to:

public func fetch(_ urlRequest: URLRequest) async throws -> UIImage {
    // ... code from the previous snippet

    if let image = try self.imageFromFileSystem(for: urlRequest) {
        images[urlRequest] = .fetched(image)
        return image
    }

    // we'll need to implement a bit more before this code compiles
}

This code calls out to a private method called imageFromFileSystem. I haven't shown you this method yet, I'll show you the implementation soon. First, I want to briefly cover what this code snippet does. It attempts to fetch the requested image from the filesystem. This is done synchronously and when an image is found we store it in the images array so that the next called of fetch(_:) will receive the image from memory rather than the filesystem.

And again, this is all done in a thread safe manner because our ImageLoader is an actor.

As promised, here's what imageFromFileSystem looks like. It's fairly straightforward:

private func imageFromFileSystem(for urlRequest: URLRequest) throws -> UIImage? {
    guard let url = fileName(for: urlRequest) else {
        assertionFailure("Unable to generate a local path for \(urlRequest)")
        return nil
    }

    let data = try Data(contentsOf: url)
    return UIImage(data: data)
}

private func fileName(for urlRequest: URLRequest) -> URL? {
    guard let fileName = urlRequest.url?.absoluteString.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed),
          let applicationSupport = FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask).first else {
              return nil
          }

    return applicationSupport.appendingPathComponent(fileName)
}

The third and last situation we might encounter is one where the image needs to be retrieved from the network. Let's see what this looks like:

public func fetch(_ urlRequest: URLRequest) async throws -> UIImage {
    // ... code from the previous snippets

    let task: Task<UIImage, Error> = Task {
        let (imageData, _) = try await URLSession.shared.data(for: urlRequest)
        let image = UIImage(data: imageData)!
        try self.persistImage(image, for: urlRequest)
        return image
    }

    images[urlRequest] = .inProgress(task)

    let image = try await task.value

    images[urlRequest] = .fetched(image)

    return image
}

private func persistImage(_ image: UIImage, for urlRequest: URLRequest) throws {
    guard let url = fileName(for: urlRequest),
          let data = image.jpegData(compressionQuality: 0.8) else {
        assertionFailure("Unable to generate a local path for \(urlRequest)")
        return
    }

    try data.write(to: url)
}

This last addition to fetch(:) creates a new Task instance to fetch image data from the network. When the data is successfully retrieved, and it's converted to an instance of UIImage. This image is then persisted to disk using the persistImage(:for:) method that I included in this snippet.

After creating the task, I update the images dictionary so it contains the newly created task. This will allow other callers of fetch(_:) to reuse this task. Next, I await the task's value and I update the images dictionary so it contains the fetched image. Lastly, I return the image.

You might be wondering why I need to add the in progress task to the images dictionary before awaiting it.

The reason is that while fetch(:) is suspended to await the networking task's value, other callers to fetch(:) will get time to run. This means that while we're awaiting the task value, someone else might call the fetch(_:) method and read the images dictionary. If the in progress task isn't added to the dictionary at that time, we would kick off a second fetch. By updating the images dictionary first, we make sure that subsequent callers will reuse the in progress task.

At this point, we have a complete image loader done. Pretty sweet, right? I'm always delightfully surprised to see how simple actors make complicated flows that require careful synchronization to correctly handle concurrent access.

Here's what the final implementation for the fetch(_:) method looks like:

public func fetch(_ urlRequest: URLRequest) async throws -> UIImage {
    if let status = images[urlRequest] {
        switch status {
        case .fetched(let image):
            return image
        case .inProgress(let task):
            return try await task.value
        }
    }

    if let image = try self.imageFromFileSystem(for: urlRequest) {
        images[urlRequest] = .fetched(image)
        return image
    }

    let task: Task<UIImage, Error> = Task {
        let (imageData, _) = try await URLSession.shared.data(for: urlRequest)
        let image = UIImage(data: imageData)!
        try self.persistImage(image, for: urlRequest)
        return image
    }

    images[urlRequest] = .inProgress(task)

    let image = try await task.value

    images[urlRequest] = .fetched(image)

    return image
}

Next up, using it in a SwiftUI view to create our own version of AsyncImage.

Building our custom SwiftUI async image view

The custom SwiftUI view that we'll create in this section is mostly intended as a proof of concept. I've tested it in a few scenarios but not thoroughly enough to say with confidence that this would be a better async image than the built-in AsyncImage. However, I'm pretty sure that this is an implementation that should work fine in many situations.

To provide our custom image view with an instance of the ImageLoader, I'll use SwiftUI's environment. To do this, we'll need to add a custom value to the EnvironmentValues object:

struct ImageLoaderKey: EnvironmentKey {
    static let defaultValue = ImageLoader()
}

extension EnvironmentValues {
    var imageLoader: ImageLoader {
        get { self[ImageLoaderKey.self] }
        set { self[ImageLoaderKey.self ] = newValue}
    }
}

This code adds an instance of ImageLoader to the SwiftUI environment, allowing us to easily access it from within our custom view.

Our SwiftUI view will be initialized with a URL or a URLRequest. To keep things simple, we'll always use a URLRequest internally.

Here's what the SwiftUI view's implementation looks like:

struct RemoteImage: View {
    private let source: URLRequest
    @State private var image: UIImage?

    @Environment(\.imageLoader) private var imageLoader

    init(source: URL) {
        self.init(source: URLRequest(url: source))
    }

    init(source: URLRequest) {
        self.source = source
    }

    var body: some View {
        Group {
            if let image = image {
                Image(uiImage: image)
            } else {
                Rectangle()
                    .background(Color.red)
            }
        }
        .task {
            await loadImage(at: source)
        }
    }

    func loadImage(at source: URLRequest) async {
        do {
            image = try await imageLoader.fetch(source)
        } catch {
            print(error)
        }
    }
}

When we're instantiating the view, we provide it with a URL or a URLRequest. When the view is first rendered, image will be nil so we'll just render a placeholder rectangle. I didn't give it any size, that would be up to the user of RemoteImage to do.

The SwiftUI view has a task modifier applied. This modifier allows us to run asynchronous work when the view is first created. In this case, we'll use a task to ask the image loader for an image. When the image is loaded, we update the @State var image which will trigger a redraw of the view.

This SwiftUI view is pretty simple and it doesn't handle things like animations or updating the image later. Some nice additions could be to add the ability to use a placeholder image, or to make the source property non-private and use an onChange modifier to kick off a new task using the Task initializer to load a new image.

I'll leave these features to be implemented by you. The point of this simple view was merely to show you how this custom image loader can be used in a SwiftUI context; not to show you how to build a fantastic fully-featured SwiftUI image view replacement.

In Summary

In this post we covered a lot of ground. I mean, a lot. You saw how you can build an ImageLoader that gracefully handles concurrent calls by making it an actor. You saw how we can keep track of both in progress fetches as well as already fetched images using a dictionary. I showed you a very simple implementation of a file system cache as well. This allows us to cache images in memory, and load from the filesystem if needed. Lastly, you saw how we can implement logic to load our image from the network if needed.

You learned that while an asynchronous function that's defined on an actor is suspended, the actor's state can be read and written by others. This means that we needed to assign our image loading task to our dictionary before awaiting the tasks result so that subsequent callers would reuse our in progress task.

After that, I showed you how you can inject the custom image loader we've built into SwiftUI's environment, and how it can be used to build a very simple custom asynchronous image view.

All in all, you've learned a lot in this post. And the best part is, in my opinion, that while the underlying logic and thought process is quite complex, Swift Concurrency allows us to express this logic in a sensible and readable way which is really awesome.

What exactly is a Combine AnyCancellable?

If you've worked with Combine in your applications you'll know what it means when I tell you that you should always retain your cancellables. Cancellables are an important part of working with Combine, similar to how disposables are an important part of working with RxSwift. Interestingly, Swift Concurrency's AsyncSequence operates without an equivalent to cancellable (with memory leaks as a result). That said, in this post we'll only focus on Combine.

For example, you might have built a publisher that wraps CLLocationManagerDelegate and exposes the user's current location with a currentLocation publisher that's a CurrentValueSubject<CLLocation, Never>. Subscribing to this publisher would look look a bit like this:

struct ViewModel {
    let locationProvider: LocationProvider
    var cancellables = Set<AnyCancellable>()

  init(locationProvider: LocationProvider) {
        self.locationProvider = locationProvider
        locationProvider.currentLocation.sink { newLocation in 
            // use newLocation
        }.store(in: &cancellables)
    }
}

For something that's so key to working with Combine, it kind of seems like cancellables are just something we deal with without really questioning it. Thats why in this post, I'd like to take a closer look at what a cancellable is, and more specifically, I'd like to look at what the enigmatic AnyCancellable that's returned by both sink and assign(to:on:) is exactly.

Understanding the purpose of cancellables in Combine

Cancellables in Combine fulfill an important part in Combine's subscription lifecycle. According to Apple, the Cancellable protocol is the following:

A protocol indicating that an activity or action supports cancellation.

Ok. That's not very useful. I mean, if supporting cancellation is all we want to do, why do we need to retain our cancellables?

If we look at the detailed description for Cancellable, you'll find that it says the following:

Calling cancel() frees up any allocated resources. It also stops side effects such as timers, network access, or disk I/O.

This still isn't great, but at least it's something. We know that an object that implements Cancellable has a cancel method that we can call to stop any in progress work. And more importantly, we know that we can expect any allocated resources to be freed up. That's really good to know.

What this doesn't really tell us is why we need to retain our cancellables in Combine. Based on the information that Apple provides there's nothing that even hints towards the need to retain cancellables.

Let's take a look at the documentation for AnyCancellable next. Maybe a Cancellable and AnyCancellable aren't quite the same even though we'd expect AnyCancellable to be nothing more than a type-erased Cancellable based on the way Apple chose to name it.

The short description explains the following:

A type-erasing cancellable object that executes a provided closure when canceled.

Ok. That's interesting. So rather it being "just" a type erased object that conforms to Cancellable, we can provide a closure to actually do something when we initialize an AnyCancellable. When we subscribe to a publisher we don't create our own AnyCancellable though, so we'll need to dig a little deeper.

There's once sentence in the AnyCancellable documentation that tells us exactly why we need to retain cancellables. It's the very last sentence in the discussion and it reads as follows:

An AnyCancellable instance automatically calls cancel() when deinitialized.

So what exactly does this tell us?

Whenever an AnyCancellable is deallocated, it will call cancel() on itself. This will run the provided closure that I mentioned earlier. It's safe to assume that this closure will ensure that any resources associated with our subscription are torn down. After all, that's what the cancel() method is supposed to do according to the Cancellable protocol.

Based on this, we can deduce that the purpose of cancellables in Combine, or rather the purpose of AnyCancellable in Combine is to associate the lifecycle of a Combine subscription to something other than the subscription completing.

When we retain a cancellable in an instance of a view model, view controller, or any other object, the lifecycle of that subscription becomes connected to that of the owner (the retaining object) itself. Whenever the owner of the cancellable is deallocated, the subscription is torn down and all resources are freed up immediately.

Note that this might not be quite intuitive when you think of that original description I quoted from the Cancellable documentation:

A protocol indicating that an activity or action supports cancellation.

Cancelling a subscription by calling cancel() on an AnyCancellable is not a graceful operation. This is already hinted at because the documentation for Cancellable mentions that "any allocated resources" will be freed up. You need to interpret this broadly.

You won't just cancel an in flight network call and be notified about it in a receiveCompletion closure. Instead, the entire subscription is torn down immediately. You will not be informed of this, and you will not be able to react to this in your receiveCompletion closure.

To sum up the purpose of cancellables in Combine, they are used to tie the lifecycle of a subscription to the object that retains the cancellable that we receive when we subscribe to a publisher.

This description might lead to you thinking that an AnyCancellable is a wrapper for a subscription. Unfortunately, that's not quite accurate. It's also not flat out wrong, but there's a bit of a nuance here; Apple chose the name AnyCancellable instead of Subscription on purpose.

What's inside an AnyCancellable exactly?

If an AnyCancellable isn't a subscription, then what it is? What's inside of an AnyCancellable?

The answer is complicated...

When I first learned Combine I was lucky enough to run into an Apple employee at a conference. We got talking about Combine, and I explained that I was working on a Combine book. I started firing off a few questions to validate my understanding of Combine and I was very lucky to get an answer or two.

One of my questions was "So is an AnyCancellable a subscription then?" and the answer was short and simple "No. It's an AnyCancellable".

You might think that's unhelpful, and I would fully understand. However, the answer is fully correct as I learned in our conversation and it makes Apple's intent with AnyCancellable perfectly clear.

Combine intentionally does not specify what's inside of AnyCancellable because we simply don't need to know exactly what is wrapped and how. All we need to know is that an AnyCancellable conforms to the Cancellable protocol, and when its cancel() method is called, all resources retained by whatever the Cancellable wrapper are released.

In practice, we know that an AnyCancellable will most likely wrap an object that conforms to Subscription and possibly also one that conforms to Subscriber. One of the two might even have a reference to a Publisher object.

We know this because we know that these three objects are always involved when you subscribe to a publisher. I've outlined this in more detail in this post as well as my Combine book.

This is really a long-winded way of me trying to tell you that we don't know what's inside an AnyCancellable, and it doesn't matter. You just need to remember that when an AnyCancellable is deallocated it will run its cancellation closure which will tear down anything it retains. This includes tearing down your subscription to a publisher.

If you're interested in learning about Swift Concurrency's AsyncSequence, and how it compares to publishers in Combine, I highly recommend that you start by looking at this post.

In Summary

In this post you learned about a key aspect of Combine; the Cancellable. I explained what the Cancellable protocol is, and from there I moved on to explain what the AnyCancellable is.

You learned that subscribing to a publisher with sink or assign(to:on:) will return an AnyCancellable that will tear down your subscription whenever the AnyCancellable is deallocated. This makes sure that your subscription to a publisher is deallocated when the object that retains your AnyCancellable is deallocated. This prevents your subscriptions from being deallocated immediately when the scope where they're created exits.

Lastly, I explained that we don't know what exactly is inside of the AnyCancellable objects that we retain for our subscriptions. While we can be pretty certain that an AnyCancellable must somehow retain a subscription, we shouldn't refer to it as a wrapper for a subscription because that would be inaccurate.

Hopefully this post gave you some extra insights into something that everybody that works with Combine has to deal with even though there's not a ton of information out there on AnyCancellable specifically.

Building a token refresh flow with async/await and Swift Concurrency

One of my favorite concurrency problems to solve is building concurrency-proof token refresh flows. Refreshing authentication tokens is something that a lot of us deal with regularly, and doing it correctly can be a pretty challenging task. Especially when you want to make sure you only issue a single token refresh request even if multiple network calls encounter the need to refresh a token.

Furthermore, you want to make sure that you automatically retry a request that failed due to a token expiration after you've obtained a new (valid) authentication token.

I wrote about a flow that does this before, except that post covered token refreshes with Combine rather than async await.

In this post, we'll build the exact same flow, except it'll use Swift Concurrency rather than Combine.

Understanding the flow

Before I dive into the implementation details, I want to outline the requirements of the token refresh flow that we'll build. The following chart outlines the flow of the network object that I want to build in this post:

A chart that describes the flow of making an authenticated network call

Whenever a network request is made, we ask an AuthManager object for a valid token. If a valid token was obtained, we can proceed with the network call. If no valid token was obtained we should present a login screen. When the request itself succeeds, we're all good and we'll return the result of the request. If the request fails due to a token error, we'll attempt to refresh the token. If the refresh succeeds, we'll retry the original request. If we couldn't refresh the token, an error is thrown. When the request is retried and it fails again we'll also throw an error even if the error is related to the token. Clearly something is wrong and it doesn't make sense to refresh and retry endlessly.

The AuthManager itself is pro-active about how it deals with tokens as shown in the following diagram:

A graph that depicts the flow of refreshing a token

When the AuthManager is asked for a valid token, we'll check if a token exists locally. If not, we'll throw an error. If it does exist, we check if the token is valid. If it isn't, a refresh is attempted so we can obtain a valid token. If this succeeds the valid token is returned. In cases where the token refresh fails we'll throw an error so the user can authenticate again.

This flow is complex enough as it is, but when we add the requirement that we should only have one request in progress at any given time, things can get a little hairy.

Luckily, Swift's concurrency features are incredibly helpful when building a flow like this.

We'll implement the AuthManager object first, and after that I'll show you how it can be used in the Network object.

Note that all of this is somewhat simplified from how you might structure things in the real world. For example, you should always store tokens in the keychain, and your objects are probably a lot more complex than the ones I'm working with in this post.

None of that changes the flow and principles of what I intend to describe, hence why I chose to go with a simplified representation because it allows you to focus on the relevant parts for this post.

Implementing the AuthManager

Because we want to make sure that our AuthManager handles concurrent calls to validToken() in such a way that we only have one refresh request in flight at any time, we should make it an actor. Actors ensure that their internal state is always accessed in a serial fashion rather than concurrently. This means that we can keep track of a currently in-flight token refresh call and check whether one exists safely as long as the manager is an actor.

If you want to learn more about Swift's actors and how they are used, I recommend you take a look at my post on actors before moving on with the implementation of AuthManager.

Now that we know we're going to make AuthManager an actor, and we already know that it needs a validToken() and a refreshToken() method, we can implement a starting point for the manager as follows:

actor AuthManager {
    private var currentToken: Token?
    private var refreshTask: Task<Token, Error>?

    func validToken() async throws -> Token {        

    }

    func refreshToken() async throws -> Token {

    }
}

This skeleton shouldn't be too surprising. Note that I'm storing the token as an instance variable on AuthManager. Do not do this in your own implementation. You should store the token in the user's Keychain, and read it from there when needed. I'm only storing it as an instance variable for convenience, not because it's good practice (because it's not).

Before we move on, I want to show you the error I might throw from within the AuthManager:

enum AuthError: Error {
    case missingToken
}

The validToken() implementation is probably the simplest implementation in this post, so let's look at that first:

func validToken() async throws -> Token {
    if let handle = refreshTask {
        return try await handle.value
    }

    guard let token = currentToken else {
        throw AuthError.missingToken
    }

    if token.isValid {
        return token
    }

    return try await refreshToken()
}

In this method, I cover four scenarios in the following order:

  1. If we're currently refreshing a token, await the value for our refresh task to make sure we return the refreshed token.
  2. We're not refreshing a token, and we don't have a persisted token. The user should log in. Note that you'd normally replace currentToken with reading the current token from the user's keychain.
  3. We found a token, and we can reasonably assume the token is valid because we haven't reached the expiration threshold yet.
  4. None of the above applies so we'll need to refresh the token.

I didn't define a network nor a keychain property in my skeleton because we won't be using them for the purposes of this post, but I can't stress enough that tokens should always be stored in the user's keychain and nowhere else.

Let's start building out the refreshToken() method next. We'll do this in two steps. First, we'll handle the case where refreshToken() is called concurrently multiple times:

func refreshToken() async throws -> Token {
    if let refreshTask = refreshTask {
        return try await refreshTask.value
    }

    // initiate a refresh...
}

Because AuthManager is an actor, this first step is relatively simple. Normally you might need a sync queue or a lock to make sure concurrent calls to refreshToken() don't cause data races on refreshTask. Actors don't have this issue because they make sure that their state is always accessed in a safe way.

We can return the result of our existing refresh task by awaiting and returning the task handle's value. We can await this value in multiple places which means that all concurrent calls to refreshToken() can (and will) await the same refresh task.

The next step is to initiate a new token refresh and store the refresh task on AuthManager. We'll also return the result of our new refresh task in this step:

func refreshToken() async throws -> Token {
    if let refreshTask = refreshTask {
        return try await refreshTask.value
    }

    let task = Task { () throws -> Token in
        defer { refreshTask = nil }

        // Normally you'd make a network call here. Could look like this:
        // return await networking.refreshToken(withRefreshToken: token.refreshToken)

        // I'm just generating a dummy token
        let tokenExpiresAt = Date().addingTimeInterval(10)
        let newToken = Token(validUntil: tokenExpiresAt, id: UUID())
        currentToken = newToken

        return newToken
    }

    self.refreshTask = task

    return try await task.value
}

In this code, I create a new Task instance so that we can store it in our AuthManager. This task can throw if refreshing the token fails, and it will update the current token when the refresh succeeds. I'm using defer to make sure that I always set my refreshTask to nil before completing the task. Note that I don't need to await access to refreshTask because this newly created Task will run on the AuthManager actor automatically due to the way Structured Concurrency works in Swift.

I assign the newly created task to my refreshTask property, and I await and return its value like I explained before showing you the code.

Even though our flow is relatively complex, it wasn't very complicated to implement this in a concurrency-proof way thanks to the way actors work in Swift.

If actors are still somewhat of a mystery to you after reading this, take a look at my post on actors to learn more.

As a next step, let's see how we can build the networking part of this flow by creating a Networking object that uses the AuthManager to obtain and refresh a valid access token and retry requests if needed.

Using the AuthManager in a Networking object

Now that we have a means of obtaining a valid token, we can use the AuthManager to add authorization to our network calls. Let's look at a skeleton of the Networking object so we have a nice starting point for the implementation:

class Networking {

    let authManager: AuthManager

    init(authManager: AuthManager) {
        self.authManager = authManager
    }

    func loadAuthorized<T: Decodable>(_ url: URL) async throws -> T {
        // we'll make the request here
    }

    private func authorizedRequest(from url: URL) async throws -> URLRequest {
        var urlRequest = URLRequest(url: url)
        let token = try await authManager.validToken()
        urlRequest.setValue("Bearer \(token.value)", forHTTPHeaderField: "Authorization")
        return urlRequest
    }
}

The code in this snippet is fairly straightforward. The Networking object depends on an AuthManager. I added a convenient function to create an authorized URLRequest from within the Networking class. We'll use this method in loadAuthorized to fetch data from an endpoint that requires authorization and we'll decode the fetched data into decodable model T. This method uses generics so we can use it to fetch decoded data from any URL that requires authorization.

If you're not familiar with generics, you can read more about them here and here.

Let's implement the happy path for our loadAuthorized method next:

func loadAuthorized<T: Decodable>(_ url: URL) async throws -> T {
    let request = try await authorizedRequest(from: url)
    let (data, _) = try await URLSession.shared.data(for: request)

    let decoder = JSONDecoder()
    let response = try decoder.decode(T.self, from: data)

    return response
}

This code should, again, be fairly straightfoward. First, I create an authorized URLRequest for the URL we need to load by calling authorizedRequest(from:). As you saw earlier, this method will ask the AuthManager for a valid token and configure an authorization header that contains an access token. We prefix the call to this method with try await because this operation can fail, and could require us to be suspended in the case that we need to perform a token refresh proactively.

If we can't authorize a request, this means that AuthManager's validToken method threw an error. This, in turn, means that we either don't have an access token at all, or we couldn't refresh our expired token. If this happens it makes sense for loadAuthorized to forward this error to its callers so they can present a login screen or handle the missing token in another appropriate way.

Next, I perform the URLRequest. A URLRequest can fail for various reason so this call needs to be prefixed with try as well. Any network related errors that get thrown from this line are forwarded to our caller.

Once we've obtained Data from the URLRequest we decode it into the appropriate type T and we return this decoded data to the caller.

Before we move on, please take a moment to appreciate how much more straightforward this code looks with async/await when compared to a traditional callback based approach or even a reactive approach that you might implement with RxSwift or Combine.

As it stands, we've implemented about half of the request flow. I've made the implemented steps green in the image below:

A graph of the networking flow with the happy path that's currently implemented highlighted in green.

To implement the last couple of steps we need to make a small change to the signature of loadAuthorized so it can take an allowRetry argument that we'll use to limit our number of retries to a single retry. We'll also need to check whether the response we received from URLSession is an HTTP 401: Unauthorized response that would indicate we ran into an authorization error so we can explicitly refresh our token one time and retry the original request.

While this should not be a common situation to be in, it's entirely possible that we believe our persisted token is valid since the device clock is pretty far from the token's expiration date while the token is, in fact, expired. One reason is that all tokens in the back-end were manually set to be expired for security reasons. It's also possible that your user's device clock was changed (either by the user or by travelling through timezones) which led to our calculations being incorrect.

In any event, we'll want to attempt a token refresh and retry the request once if this happens.

Here's what the updated loadAuthorized method looks like:

func loadAuthorized<T: Decodable>(_ url: URL, allowRetry: Bool = true) async throws -> T {
    let request = try await authorizedRequest(from: url)
    let (data, urlResponse) = try await URLSession.shared.data(for: request)

    // check the http status code and refresh + retry if we received 401 Unauthorized
    if let httpResponse = urlResponse as? HTTPURLResponse, httpResponse.statusCode == 401 {
        if allowRetry {
            _ = try await authManager.refreshToken()
            return try await loadAuthorized(url, allowRetry: false)
        }

        throw AuthError.invalidToken
    }

    let decoder = JSONDecoder()
    let response = try decoder.decode(T.self, from: data)

    return response
}

These couple of lines of code that I added implement the last part of our flow. If we couldn't make the request due to a token error we'll refresh the token explicitly and we retry the request once. If we're not allowed to retry the request I throw an invalidToken error to signal that we've attempted to make a request with a token that we believe is valid yet we received an HTTP 401: Unauthorized.

Of course, this is a somewhat simplified approach. You might want to take the HTTP body for any non-200 response and decode it into an Error object that you throw from your loadAuthorized method instead of doing what I did here. The core principle of implementing a mechanism that will proactively refresh your auth tokens and authorize your network requests shouldn't change no matter how you decide to deal with specific status codes.

All in all, Swift Concurrency's actors combined with async/await allowed us to build a complex asynchronous flow by writing code that looks like it's imperative code while there's actually a ton of asynchronisity and even synchronization happening under the hood. Pretty cool, right?

In Summary

In this post, you saw how I implemented one of my favorite networking and concurrency related examples with async/await and actors. First, you learned what the flow we wanted to implement looks like. Next, I showed you how we can leverage Swift's actors to build a concurrency proof token provider that I called an AuthManager. No matter how many token related methods we call concurrently on this object, it will always make sure that we only have one refresh call in progress at any given time.

After that, you saw how you can leverage this AuthManager in a Networking object to authorize network calls and even explicitly refresh a token and retry the original request whenever we encounter an unexpected token related error.

Flows like these are a really nice way to experiment with, and learn about, Swift Concurrency features because they can be applied in the real world immediately, and they force you to mix and match different concurrency features so you'll immediately see how things fit together in the real world.

Using Swift Concurrency’s task group for tasks with varying output

Earlier, I published a post on Swift Concurrency's task groups. If you haven't read that post yet, and you're not familiar with task groups, I recommend that you read that post first because I won't be explaining task groups in this post. Instead, you will learn about a technique that you can use to work around a limitation of task groups.

Task groups can run a number of child tasks where every child task in the task group produces the same output. This is a hard requirement of the withTaskGroup function. This means that task groups are not the right tool for every job. Sometimes it makes more sense to use async let instead.

In the post where I introduced task groups, I used an example where I needed to fetch a Movie object based on an array of UUIDs. Now let's imagine that our requirements aren't as clear, and we write a function where we receive an array of Descriptor objects that informs us about the type of objects we need to load.

These objects could be either a Movie, or a TVShow. Here's what the Descriptor looks like:

enum MediaType {
    case movie, tvShow
}

struct Descriptor {
    let id: UUID
    let type: MediaType
}

The implementation of Movie and TVShow aren't really relevant in this context. All you need to know is that they can both be loaded from a remote source based on a UUID.

Now let's take a look at the skeleton function that we'll work with:

func fetchMedia(descriptors: [Descriptor]) async -> ???? {
    return await withTaskGroup(of: ????) { group in 
        for descriptor in descriptor {
            group.addTask {
                // do work and return something
            }
        }
    }
}

Notice that I used ???? instead of an actual type for the function's return type and for the type of the task group. We'll need to figure out what we want to return.

One approach would be to create a Media base class and have Movie and TVShow subclass this object. That would work in this case, but it requires us to use classes where we might prefer structs, and it wouldn't work if the the fetched objects weren't so similar.

Instead, we can define an enum and use that as our task output and return type instead. Let's call it a TaskResult:

enum TaskResult {
    case movie(Movie)
    case tvShow(TVShow)
}

Now we can switch on the Descriptor's type, fetch our object, and return a TaskResult where the fetched media is an associated type of our enum case:

func fetchMedia(descriptors: [Descriptor]) async -> [TaskResult] {
    return await withTaskGroup(of: TaskResult.self) { group in 
        for descriptor in descriptor {
            group.addTask {
                switch descriptor.type {
                    case .movie:
                        let movie = await self.fetchMovie(id: descriptor.id)
                        return TaskResult.movie(movie)
                    case .tvShow:
                        let tvShow = await self.fetchShow(id: descriptor.id)
                        return TaskResult.tvShow(tvShow)
                }
            }
        }

        var results = [TaskResult]()

        for await result in group {
            results.append(result)
        }

        return results
    }
}

The nice thing about this approach is that it's easy to scale it into as many types as you need without the need to subclass. That said, I wouldn't recommend this approach in all cases. For example, if you're building a flow similar to the one I show in my post on async let, task groups wouldn't make a lot of sense.

In Summary

Ideally, you only use task groups when all tasks in the group really produce the same output. However, I'm sure there are situations where you need to run an unknown number of tasks based on some input like an array where the tasks don't always produce the same output. In those cases it makes sense to apply the workaround that I've demonstrated in this post.