What are Sendable and @Sendable closures in Swift?

One of the goals of the Swift team with Swift’s concurrency features is to provide a model that allows developer to write safe code by default. This means that there’s a lot of time and energy invested into making sure that the Swift compiler helps developers detect, and prevent whole classes of bugs and concurrency issues altogether.

One of the features that helps you prevent data races (a common concurrency issue) comes in the form of actors which I’ve written about before.

While actors are great when you want to synchronize access to some mutable state, they don’t solve every possible issue you might have in concurrent code.

In this post, we’re going to take a closer look at the Sendable protocol, and the @Sendable annotation for closures. By the end of this post, you should have a good understanding of the problems that Sendable (and @Sendable) aim to solve, how they work, and how you can use them in your code.

Understanding the problems solved by Sendable

One of the trickiest aspects of a concurrent program is to ensure data consistency. Or in other words, thread safety. When we pass instances of classes or structs, enum cases, or even closures around in an application that doesn’t do much concurrent work, we don’t need to worry about thread safety a lot. In apps that don’t really perform concurrent work, it’s unlikely that two tasks attempt to access and / or mutate a piece of state at the exact same time. (But not impossible)

For example, you might be grabbing data from the network, and then passing the obtained data around to a couple of functions on your main thread.

Due to the nature of the main thread, you can safely assume that all of your code runs sequentially, and no two processes in your application will be working on the same referencea at the same time, potentially creating a data race.

To briefly define a data race, it’s when two or more parts of your code attempt to access the same data in memory, and at least one of these accesses is a write action. When this happens, you can never be certain about the order in which the reads and writes happen, and you can even run into crashes for bad memory accesses. All in all, data races are no fun.

While actors are a fantastic way to build objects that correctly isolate and synchronize access to their mutable state, they can’t solve all of our data races. And more importantly, it might not be reasonable for you to rewrite all of your code to make use of actors.

Consider something like the following code:

class FormatterCache {
    var formatters = [String: DateFormatter]()

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

        let formatter = DateFormatter()
        formatter.dateFormat = format
        formatters[format] = formatter

        return formatter
    }
}

func performWork() async {
    let cache = FormatterCache()
    let possibleFormatters = ["YYYYMMDD", "YYYY", "YYYY-MM-DD"]

    await withTaskGroup(of: Void.self) { group in
        for _ in 0..<10 {
            group.addTask {
                let format = possibleFormatters.randomElement()!
                let formatter = cache.formatter(for: format)
            }
        }
    }
}

On first glance, this code might not look too bad. We have a class that acts as a simple cache for date formatters, and we have a task group that will run a bunch of code in parallel. Each task will grab a random date format from the list of possible format and asks the cache for a date formatter.

Ideally, we expect the formatter cache to only create one date formatter for each date format, and return a cached formatter after a formatter has been created.

However, because our tasks run in parallel there’s a chance for data races here. One quick fix would be to make our FormatterCache an actor and this would solve our potential data race. While that would be a good solution (and actually the best solution if you ask me) the compiler tells us something else when we try to compile the code above:

Capture of 'cache' with non-sendable type 'FormatterCache' in a @Sendable closure

This warning is trying to tell us that we’re doing something that’s potentially dangerous. We’re capturing a value that cannot be safely passed through concurrency boundaries in a closure that’s supposed to be safely passed through concurrency boundaries.

⚠️ If the example above does not produce a warning for you, you'll want to enable strict concurrency checking in your project's build settings for stricter Sendable checks (amongst other concurrency checks). You can enable strict concurrecy settings in your target's build settings. Take a look at this page if you're not sure how to do this.

Being able to be safely passed through concurrency boundaries essentially means that a value can be safely accessed and mutated from multiple tasks concurrently without causing data races. Swift uses the Sendable protocol and the @Sendable annotation to communicate this thread-safety requirement to the compiler, and the compiler can then check whether an object is indeed Sendable by meeting the Sendable requirements.

What these requirements are exactly will vary a little depending on the type of objects you deal with. For example, actor objects are Sendable by default because they have data safety built-in.

Let’s take a look at other types of objects to see what their Sendable requirements are exactly.

Sendable and value types

In Swift, value types provide a lot of thread safety out of the box. When you pass a value type from one place to the next, a copy is created which means that each place that holds a copy of your value type can freely mutate its copy without affecting other parts of the code.

This a huge benefit of structs over classes because they allow use to reason locally about our code without having to consider whether other parts of our code have a reference to the same instance of our object.

Because of this behavior, value types like structs and enums are Sendable by default as long as all of their members are also Sendable.

Let’s look at an example:

// This struct is not sendable
struct Movie {
    let formatterCache = FormatterCache()
    let releaseDate = Date()
    var formattedReleaseDate: String {
        let formatter = formatterCache.formatter(for: "YYYY")
        return formatter.string(from: releaseDate)
    }
}

// This struct is sendable
struct Movie {
    var formattedReleaseDate = "2022"
}

I know that this example is a little weird; they don’t have the exact same functionality but that’s not the point.

The point is that the first struct does not really hold mutable state; all of its properties are either constants, or they are computed properties. However, FormatterCache is a class that isn't Sendable. Since our Movie struct doesn’t hold a copy of the FormatterCache but a reference, all copies of Movie would be looking at the same instances of the FormatterCache, which means that we might be looking at data races if multiple Movie copies would attempt to, for example, interact with the formatterCache.

The second struct only holds Sendable state. String is Sendable and since it’s the only property defined on Movie, movie is also Sendable.

The rule here is that all value types are Sendable as long as their members are also Sendable.

Generally speaking, the compiler will infer your structs to be Sendable when needed. However, you can manually add Sendable conformance if you'd like:

struct Movie: Sendable {
    let formatterCache = FormatterCache()
    let releaseDate = Date()
    var formattedReleaseDate: String {
        let formatter = formatterCache.formatter(for: "YYYY")
        return formatter.string(from: releaseDate)
    }
}

Sendable and classes

While both structs and actors are implicitly Sendable, classes are not. That’s because classes are a lot less safe by their nature; everybody that receives an instance of a class actually receives a reference to that instance. This means that multiple places in your code hold a reference to the exact same memory location and all mutations you make on a class instance are shared amongst everybody that holds a reference to that class instance.

That doesn’t mean we can’t make our classes Sendable, it just means that we need to add the conformance manually, and manually ensure that our classes are actually Sendable.

We can make our classes Sendable by adding conformance to the Sendable protocol:

final class Movie: Sendable {
    let formattedReleaseDate = "2022"
}

The requirements for a class to be Sendable are similar to those for a struct.

For example, a class can only be Sendable if all of its members are Sendable. This means that they must either be Sendable classes, value types, or actors. This requirement is identical to the requirements for Sendable structs.

In addition to this requirement, your class must be final. Inheritance might break your Sendable conformance if a subclass adds incompatible overrides or features. For this reason, only final classes can be made Sendable.

Lastly, your Sendable class should not hold any mutable state. Mutable state would mean that multiple tasks can attempt to mutate your state, leading to a data race.

However, there are instances where we might know a class or struct is safe to be passed across concurrency boundaries even when the compiler can’t prove it.

In those cases, we can fall back on unchecked Sendable conformance.

Unchecked Sendable conformance

When you’re working with codebases that predate Swift Concurrency, chances are that you’re slowly working your way through your app in order to introduce concurrency features. This means that some of your objects will need to work in your async code, as well as in your sync code. This means that using actor to isolate mutable state in a reference type might not work so you’re stuck with a class that can’t conform to Sendable. For example, you might have something like the following code:

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

    func formatter(for format: String) -> DateFormatter {
        return queue.sync {
            if let formatter = formatters[format] {
                return formatter
            }

            let formatter = DateFormatter()
            formatter.dateFormat = format
            formatters[format] = formatter

            return formatter
        }
    }
}

This formatter cache uses a serial queue to ensure synchronized access to its formatters dictionary. While the implementation isn’t ideal (we could be using a barrier or maybe even a plain old lock instead), it works. However, we can’t add Sendable conformance to our class because formatters isn’t Sendable.

To fix this, we can add @unchecked Sendable conformance to our FormatterCache:

class FormatterCache: @unchecked Sendable {
    // implementation unchanged
}

By adding this @unchecked Sendable we’re instructing the compiler to assume that our FormatterCache is Sendable even when it doesn’t meet all of the requirements.

Having this feature in our toolbox is incredibly useful when you’re slowly phasing Swift Concurrency into an existing project, but you’ll want to think twice, or maybe even three times, when you’re reaching for @unchecked Sendable. You should only use this feature when you’re really certain that your code is actually safe to be used in a concurrent environment.

Using @Sendable on closures

There’s one last place where Sendable comes into play and that’s on functions and closures.

Lots of closures in Swift Concurrency are annotated with the @Sendable annotation. For example, here’s what the declaration for TaskGroup's addTask looks like:

public mutating func addTask(priority: TaskPriority? = nil, operation: @escaping @Sendable () async -> ChildTaskResult)

The operation closure that’s passed to addTask is marked with @Sendable. This means that any state that the closure captures must be Sendable because the closure might be passed across concurrency boundaries.

In other words, this closure will run in a concurrent manner so we want to make sure that we’re not accidentally introducing a data race. If all state captured by the closure is Sendable, then we know for sure that the closure itself is Sendable. Or in other words, we know that the closure can safely be passed around in a concurrent environment.

Tip: to learn more about closures in Swift, take a look at my post that explains closures in great detail.

Summary

In this post, you’ve learned about the Sendable and @Sendable features of Swift Concurrency. You learned why concurrent programs require extra safety around mutable state, and state that’s passed across concurrency boundaries in order to avoid data races.

You learned that structs are implicitly Sendable if all of their members are Sendable. You also learned that classes can be made Sendable as long as they’re final, and as long as all of their members are also Sendable.

Lastly, you learned that the @Sendable annotation for closures helps the compiler ensure that all state captured in a closure is Sendable and that it’s safe to call that closure in a concurrent context.

I hope you’ve enjoyed this post. If you have any questions, feedback, or suggestions to help me improve the reference then feel free to reach out to me on Twitter.

Xcode 14 “Publishing changes from within view updates is not allowed, this will cause undefined behavior”

UPDATE FOR XCODE 14.1: This issue appears to have been partially fixed in Xcode 14.1. Some occurences of the warning are fixed, others aren't. In this post I'm collecting situations me and others run into and track whether they are fixed or not. If you have another sample that you think is similar, please send a sample of your code on Twitter as a Github Gist.


Dear reader, if you've found this page you're probably encountering the error from the post title. Let me start by saying this post does not offer you a quick fix. Instead, it serves to show you the instance where I ran into this issue in Xcode 14, and why I believe this issue is a bug and not an actual issue. I've last tested this with Xcode 14.0's Release Candidate. I've filed feedback with Apple, the feedback number is FB11278036 in case you want to duplicate my issue.

Some of the SwiftUI code that I've been using fine for a long time now has recently started coming up with this purple warning.

Screenshot of "Publishing changes from within view updates is not allowed, this will cause undefined behavior." purple warning

Initially I thought that there was a chance that I was, in fact, doing something weird all along and I started chipping away at my project until I had something that was small enough to only cover a few lines, but still complex enough to represent the real world.

In this post I've collected some example of where I and other encounter this issue, along with whether it's been fixed or not.

[Fixed] Purple warnings when updating an @Published var from a Button in a List.

In my case, the issue happened with the following code:

class SampleObject: ObservableObject {
    @Published var publishedProp = 1337

    func mutate() {
        publishedProp = Int.random(in: 0...50)
    }
}

struct CellView: View {
    @ObservedObject var dataSource: SampleObject

    var body: some View {
        VStack {
            Button(action: {
                dataSource.mutate()
            }, label: {
                Text("Update property")
            })

            Text("\(dataSource.publishedProp)")
        }
    }
}

struct ContentView: View {
    @StateObject var dataSource = SampleObject()

    var body: some View {
        List {
            CellView(dataSource: dataSource)
        }
    }
}

This code really does nothing outrageous or weird. A tap on a button will simply mutate an @Published property, and I expect the list to update. Nothing fancy. However, this code still throws up the purple warning. Compiling this same project in Xcode 13.4.1 works fine, and older Xcode 14 betas also don't complain.

At this point, it seems like this might be a bug in List specifically because changing the list to a VStack or LazyVStack in a ScrollView does not give me the same warning. This tells me that there is nothing fundamentally wrong with the setup above.

Another thing that seems to work around this warning is to change the type of button that triggers the action. For example, using a bordered button as shown below also runs without the warning:

Button(action: {
    dataSource.mutate()
}, label: {
    Text("Update property")
}).buttonStyle(.bordered)

Or if you want your button to look like the default button style on iOS, you can use borderless:

Button(action: {
    dataSource.mutate()
}, label: {
    Text("Update property")
}).buttonStyle(.borderless)

It kind of looks like anything except a default Button in a List is fine.

For those reasons, I sadly cannot give you a proper fix for this issue. The things I mentioned are all workarounds IMO because the original code should work. All I can say is please file a feedback ticket with Apple so we can hopefully get this fixed, documented, or otherwise explained. I'll be requesting a code level support ticket from Apple to see if an Apple engineer can help me figure this out.

Animating a map's position in SwiftUI

A Map in SwiftUI is presented using the following code:

struct ContentView: View {
    @State var currentMapRegion = MKCoordinateRegion(center: CLLocationCoordinate2D(latitude: 10.0, longitude: 0.0), span: MKCoordinateSpan(latitudeDelta: 100, longitudeDelta: 100))

    var body: some View {
        VStack {
            Map(coordinateRegion: $currentMapRegion, annotationItems: allFriends) { friend in
                MapAnnotation(coordinate: CLLocationCoordinate2D(latitude: 0, longitude: 0)) {
                    Circle()
                        .frame(width: 20, height: 20)
                        .foregroundColor(.red)
                }
            }
        }
        .ignoresSafeArea()
    }
}

Notice how the Map takes a Binding for its coordinateRegion. This means that whenever the map changes what we're looking at, our @State can update and the other way around. We can assign a new MKCoordinateRegion to our @State property and the Map will update to show the new location. It does this without animating the change. So let's say we do want to animate to a new position. For example, by doing the following:

var body: some View {
    VStack {
        Map(coordinateRegion: $currentMapRegion, annotationItems: allFriends) { friend in
            MapAnnotation(coordinate: CLLocationCoordinate2D(latitude: friend.cityLatitude ?? 0, longitude: friend.cityLongitude ?? 0)) {
                Circle()
                    .frame(width: 20, height: 20)
                    .foregroundColor(.red)
            }
        }
    }
    .ignoresSafeArea()
    .onAppear {
        DispatchQueue.main.asyncAfter(deadline: .now() + 3) {
            withAnimation {
                currentMapRegion = MKCoordinateRegion(center: CLLocationCoordinate2D(latitude: 80, longitude: 80),
                                                      span: MKCoordinateSpan(latitudeDelta: 100, longitudeDelta: 100))
            }
        }
    }
}

This code applies some delay and then eventually moves the map to a new position. The animation could also be triggered by a Button or really anything else; how we trigger the animation isn't the point.

When the animation runs, we see lots and lots of warnings in the console (187 for me...) and they all say [SwiftUI] Publishing changes from within view updates is not allowed, this will cause undefined behavior..

We're clearly just updating our currentMapRegion just once, and putting print statements in the onAppear tells us that the onAppear and the withAnimation block are all called exactly once.

I suspected that the Map itself was updating its binding to animate from one position to the next so I changed the Map setup code a little:

Map(coordinateRegion: Binding(get: {
    self.currentMapRegion
}, set: { newValue, _ in
    print("\(Date()) assigning new value \(newValue)")
    self.currentMapRegion = newValue
}), annotationItems: allFriends) { friend in
    MapAnnotation(coordinate: CLLocationCoordinate2D(latitude: friend.cityLatitude ?? 0, longitude: friend.cityLongitude ?? 0)) {
        Circle()
            .frame(width: 20, height: 20)
            .foregroundColor(.red)
    }
}

Instead of directly binding to the currentMapRegion property, I made a custom instance of Binding that allows me to intercept any write operations to see how many occur and why. Running the code with this in place, yields an interesting result:

2022-10-26 08:38:39 +0000 assigning new value MKCoordinateRegion(center: __C.CLLocationCoordinate2D(latitude: 62.973218679210305, longitude: 79.83448028564462), span: __C.MKCoordinateSpan(latitudeDelta: 89.49072082474844, longitudeDelta: 89.0964063502501))
2022-10-26 10:38:39.169480+0200 MapBug[10097:899178] [SwiftUI] Publishing changes from within view updates is not allowed, this will cause undefined behavior.
2022-10-26 10:38:39.169692+0200 MapBug[10097:899178] [SwiftUI] Publishing changes from within view updates is not allowed, this will cause undefined behavior.
2022-10-26 10:38:39.169874+0200 MapBug[10097:899178] [SwiftUI] Publishing changes from within view updates is not allowed, this will cause undefined behavior.
2022-10-26 08:38:39 +0000 assigning new value MKCoordinateRegion(center: __C.CLLocationCoordinate2D(latitude: 63.02444217894995, longitude: 79.96021270751967), span: __C.MKCoordinateSpan(latitudeDelta: 89.39019889305074, longitudeDelta: 89.09640635025013))
2022-10-26 10:38:39.186402+0200 MapBug[10097:899178] [SwiftUI] Publishing changes from within view updates is not allowed, this will cause undefined behavior.
2022-10-26 10:38:39.186603+0200 MapBug[10097:899178] [SwiftUI] Publishing changes from within view updates is not allowed, this will cause undefined behavior.
2022-10-26 10:38:39.186785+0200 MapBug[10097:899178] [SwiftUI] Publishing changes from within view updates is not allowed, this will cause undefined behavior.
2022-10-26 08:38:39 +0000 assigning new value MKCoordinateRegion(center: __C.CLLocationCoordinate2D(latitude: 63.04063284402105, longitude: 80.00000000000011), span: __C.MKCoordinateSpan(latitudeDelta: 89.35838016069978, longitudeDelta: 89.0964063502501))
2022-10-26 10:38:39.200000+0200 MapBug[10097:899178] [SwiftUI] Publishing changes from within view updates is not allowed, this will cause undefined behavior.
2022-10-26 10:38:39.200369+0200 MapBug[10097:899178] [SwiftUI] Publishing changes from within view updates is not allowed, this will cause undefined behavior.
2022-10-26 10:38:39.200681+0200 MapBug[10097:899178] [SwiftUI] Publishing changes from within view updates is not allowed, this will cause undefined behavior.

This is just a small part of the output of course but we can clearly see that the print from the custom Binding is executed in between warnings.

I can only conclude that this has to be some issue in Map that we cannot solve ourselves. You might be able to tweak the custom binding a bunch to throttle how often it actually updates the underlying @State but I'm not sure that's what we should want...

If you're seeing this issue too, you can reference FB11720091 in feedback that you file with Apple.

Huge thanks to Tim Isenman for sending me this sample.

What are primary associated types in Swift 5.7?

Swift 5.7 introduces many new features that involve generics and protocols. In this post, we're going to explore an extremely powerful new features that's called "primary associated types". By the end of this post you will know and understand what primary associated types are, and why I think they are extremely important and powerful to help you write better code.

If your familiar with Swift 5.6 or earlier, you might know that protocols with associated types have always been somewhat of an interesting beast. They were hard to use sometimes, and before Swift 5.1 we would always have to resort to using generics whenever we wanted to make use of a protocol with an associated type. Consider the following example:

class MusicPlayer {
  func play(_ playlist: Collection) { /* ... */ } 
}

This example doesn't compile in Swift 5.1, and it still wouldn’t today in Swift 5.7. The reason is that Collection has various associated types that the compiler must be able to fill in if we want to use Collection. For example, we need to what kind of Element our collection holds.

A common workaround to use protocols with associated types in our code is to use a generic that's constrained to a protocol:

class MusicPlayer<Playlist: Collection> {
  func play(_ playlist: Playlist) { /* ... */ } 
}

If you're not quite sure what this example does, take a look at this post I wrote to learn more about using generics and associated types.

Instead of using Collection as an existential (a box that holds an object that conforms to Collection) we use Collection as a constraint on a generic type that we called Playlist. This means that the compiler will always know which object is used to fill in Playlist.

In Swift 5.1, the some keyword was introduced which, combined with Swift 5.7's capability to use the some keyword on function arguments, allows us to write the following:

class MusicPlayer {
  func play(_ playlist: some Collection) { /* ... */ } 
}

To learn more about the some keyword, I recommend you take a look at this post that explains everything you need to know about some.

This is nice, but both the generic solution and the some solution have an important issue. We don’t know what’s inside of the Collection. Could be String, could be Track, could be Album, there’s no way to know. This makes func play(_ playlist: some Collection) practically useless for our MusicPlayer.

In Swift 5.7, protocols can specify primary associated types. These associated types are a lot like generics. They allow developers to specify the type for a given associated type as a generic constraint.

For Collection, the Swift library added a primary associated type for the Element associated type.

This means that you can specify the element that must be in a Collection when you pass it to a function like our func play(_ playlist: some Collection). Before I show you how, let’s take a look at how a protocol defines a primary associated type:

public protocol Collection<Element> : Sequence {

  associatedtype Element
  associatedtype Iterator = IndexingIterator<Self>
  associatedtype SubSequence : Collection = Slice<Self> where Self.Element == Self.SubSequence.Element, Self.SubSequence == Self.SubSequence.SubSequence

  // a lot of other stuff
}

Notice how the protocol has multiple associated types but only Element is written between <> on the Collection protocol. That’s because Element is a primary associated type. When working with a collection, we often don’t care what kind of Iterator it makes. We just want to know what’s inside of the Collection!

So to specialize our playlist, we can write the following code:

class MusicPlayer {
  func play(_ playlist: some Collection<Track>) { /* ... */ }
}

Note that the above is functionally equivalent to the following if Playlist is only used in one place:

class MusicPlayer {
  func play<Playlist: Collection<Track>>(_ playlist: Playlist) { /* ... */ }
}

While the two snippets above are equivalent in functionallity the former option that uses some is preferred. The reason for this is that code with some is easier to read and reason about than having a generic that doesn't need to be a generic.

Note that this also works with the any keyword. For example, if we want to store our playlist on our MusicPlayer, we could write the following code:

class MusicPlayer {
    var playlist: any Collection<Track> = []

    func play(_ playlist: some Collection<Track>) {
        self.playlist = playlist
    }
}

With primary associated types we can write much more expressive and powerful code, and I’m very happy to see this addition to the Swift language.

What’s the difference between any and some in Swift 5.7?

Protocols are an extremely important part in the Swift language, and in recent updates we've received some new capabilities around protocol and generics that allow us to be much more intentional about how we use protocols in our code. This is done through the any and some keywords.

In this post, you will learn everything you need to know about the similarities and differences between these two keywords. We'll start with an introduction of each keyword, and then you'll learn a bit more about the problems each keyword solves, and how you can decide whether you should use some or any in your code.

The some keyword

In Swift 5.1 Apple introduced the some keyword. This keyword was key in making SwiftUI work because the View protocol defines an associated type which means that the View protocol couldn't be used as a type.

The following code shows how the View protocol is defined. As you'll notice, there's an associated type Body:

protocol View {
  associatedtype Body: View
  @ViewBuilder @MainActor var body: Self.Body { get }
}

If you’d try to write var body: View instead of var body: some View you’d see the following compiler error in Swift 5.7:

Use of protocol 'View' as a type must be written 'any View’

Or in older versions of Swift you’d see the following:

protocol can only be used as a generic constraint because it has Self or associated type requirements

The some keyword fixes this by hiding the concrete associated type from whoever interacts with the object that has some Protocol as its type. More on this later.

For a full overview of the some keyword, please refer to this post.

The any keyword

In Swift 5.6, the any keyword was added to the Swift language.

While it sounds like the any keyword acts as a type erasing helper, all it really does is inform the compiler that you opt-in to using an existential (a box type that conforms to a protocol) as your type.

Code that you would originally write as:

func getObject() -> SomeProtocol {
  /* ... */
}

Should be written as follows in Swift 5.6 and above:

func getObject() -> any SomeProtocol {
  /* ... */
}

This makes it explicit that the type you return from getObject is an existential (a box type) rather than a concrete object that was resolved at compile time. Note that using any is not mandatory yet, but you should start using it. Swift 6.0 will enforce any on existentials like the one that's used in the example you just saw.

Since both any and some are applied to protocols, I want to put them side by side in this blog post to better explain the problems they solve, and how you should decide whether you should use any, some, or something else.

For a full overview of the any keyword, please refer to this post.

Understanding the problems that any and some solve

To explain the problems solved by any we should look at a somewhat unified example that will allow us to cover both keywords in a way that makes sense. Imagine the following protocol that models a Pizza:

protocol Pizza {
    var size: Int { get }
    var name: String { get }
}

It’s a simple protocol but it’s all we need. In Swift 5.6 you might have written the following function to receive a Pizza:

func receivePizza(_ pizza: Pizza) {
    print("Omnomnom, that's a nice \(pizza.name)")
}

When this function is called, the receivePizza function receives a so-called box type for Pizza. In order to access the pizza name, Swift has to open up that box, grab the concrete object that implements the Pizza protocol, and then access name. This means that there are virtually no compile time optimizations on Pizza, making the receivePizza method more expensive than we’d like.

Furthermore, the following function looks pretty much the same, right?

func receivePizza<T: Pizza>(_ pizza: T) {
    print("Omnomnom, that's a nice \(pizza.name)")
}

There’s a major difference here though. The Pizza protocol isn’t used as a type here. It’s used as a constraint for T. The compiler will be able to resolve the type of T at compile time and receivePizza will receive a concrete instance of a type rather than a box type.

Because this difference isn’t always clear, the Swift team has introduced the any keyword. This keyword does not add any new functionality. Instead, it forces us to clearly communicate “this is an existential”:

func receivePizza(_ pizza: any Pizza) {
    print("Omnomnom, that's a nice \(pizza.name)")
}

The example that uses a generic <T: Pizza> does not need the any keyword because Pizza is used as a constraint and not as an existential.

Now that we have a clearer picture regarding any, let’s take a closer look at some.

In Swift, many developers have tried to write code like this:

let someCollection: Collection

Only to be faced by a compiler error to tell them that Collection has a Self or associated type requirement. In Swift 5.1 we can write some Collection to tell the compiler that anybody that accesses someCollection should not concern themselves with the specifics of the associated type and/or the Self requirement. They should just know that this thing conforms to Collection and that’s all. There's no information about the associated type, and the information about Self is not made available.

This mechanism is essential to making SwiftUI’s View protocol work.

The downside of course is that anybody that works with a some Collection, some Publisher, or some View can’t access any of the generic specializations. That problem is solved by primary associated types which you can read more about right here.

However, not all protocols have associated type requirements. For example, our Pizza protocol does not have an associated type requirement but it can benefit from some in certain cases.

Consider this receivePizza version again:

func receivePizza<T: Pizza>(_ pizza: T) {
    print("Omnomnom, that's a nice \(pizza.name)")
}

We defined a generic T to allow the compiler to optimize for a given concrete type of Pizza. The some keyword also allows the compiler to know at compile time what the underlying type for the some object will be; it just hides this from the user of the object. This is exactly what <T: Pizza> also does. We can only access on T what is exposed by Pizza. This means that we can rewrite receivePizza<T: Pizza>(_:) as follows:

func receivePizza(_ pizza: some Pizza) {
    print("Omnomnom, that's a nice \(pizza.name)")
}

We don’t need T anywhere else, so we don’t need to “create” a type to hold our pizza. We can just say “this function takes some Pizza" instead of “this function takes some Pizza that we’ll call T". Small difference, but much easier to write. And functionally equivalent.

Choosing between any and some

Once you understand the use cases for any and some, you’ll realize that it’s not a matter of choosing one over the other. They each solve their own very similar problems and there’s always a more correct choice.

Generally speaking you should prefer using some or generics over any whenever you can. You often don’t want to use a box that conforms to a protocol; you want the object that conforms to the protocol.

Or sticking with our pizza analogy, any will hand the runtime a box that says Pizza and it will need to open the box to see which pizza is inside. With some or generics, the runtime will know exactly which pizza it just got, and it’ll know immediately what to do with it (toss if it’s Hawaii, keep if it’s pepperoni).

In lots of cases you’ll find that you actually didn’t mean to use any but can make some or a generic work, and according to the Swift team, we should always prefer not using any if we can.

Making the decision in practice

Let’s illustrate this with one more example that draws heavily from my explanation of primary associated types. You’ll want to read that first to fully understand this example:

class MusicPlayer {
    var playlist: any Collection<String> = []

    func play(_ playlist: some Collection<String>) {
        self.playlist = playlist
    }
}

In this code, I use some Collection<String> instead of writing func play<T: Collection<String>>(_ playlist: T) because the generic is only used in one place.

My var playlist is an any Collection<String> and not a some Collection<String> for two reasons:

  1. There would be no way to ensure that the concrete collection that the compiler will deduce for the play method matches the concrete collection that’s deduced for var playlist; this means they might not be the same which would be a problem.
  2. The compiler can’t deduce what var playlist: some Collection<String> in the first place (try it, you’ll get a compiler error)

We could avoid any and write the following MusicPlayer:

class MusicPlayer<T: Collection<String>> {
    var playlist: T = []

    func play(_ playlist: T) {
        self.playlist = playlist
    }
}

But this will force us to always use the same type of collection for T. We could use a Set, an Array, or another Collection but we can never assign a Set to playlist if T was inferred to be an Array. With the implementation as it was before, we can:

class MusicPlayer {
    var playlist: any Collection<String> = []

    func play(_ playlist: some Collection<String>) {
        self.playlist = playlist
    }
}

By using any Collection<String> here we can start out with an Array but pass a Set to play, it’s all good as long as the passed object is a Collection with String elements.

In Summary

While some and any sound very complex (and they honestly are), they are also very powerful and important parts of Swift 5.7. It’s worth trying to understand them both because you’ll gain a much better understanding about how Swift deals with generics and protocols. Mastering these topics will really take your coding to the next level.

For now, know that some or generics should be preferred over any if it makes sense. The any keyword should only be used when you really want to use that existential or box type where you’ll need to peek into the box at runtime to see what’s inside so you can call methods and access properties on it.

Presenting a partially visible bottom sheet in SwiftUI on iOS 16

This post is up to date for Xcode 15 and newer. It supersedes a version of this post that you can find here

On iOS 15, Apple granted developers the ability to present partially visible bottom sheets using a component called UISheetPresentationController. Originally, we had to resort to using a UIHostingController to bring this component to SwiftUI.

With iOS 16, we don't have to do this anymore. You can make use of the presentationDetents view modifier to configure your sheets to be fully visible, approximately half visible, or some custom fraction of the screen's height.

To do this, you can apply the presentationDetents modifier by applying it to your sheet's content:

struct DetentsView: View {
    @State var isShowingSheet = false

    var body: some View {
        Button("Show the sheet!") {
            isShowingSheet = true
        }
        .sheet(isPresented: $isShowingSheet) {
            ZStack {
                Color(red: 0.95, green: 0.9, blue: 1)
                Text("This is my sheet. It could be a whole view, or just a text.")
            }
            .presentationDetents([.medium, .fraction(0.7)])
        }
    }
}

Here's what the sheet looks like when it's presented on an iPhone:

An example of a bottom sheet on iPhone

In this example, my sheet will initially take up about half the screen and can be expanded to 70% of the screen height. If I want to allow the user to expand my sheet to the full height of the screen I would add the .large option to the list of presentationDetents.

By default, sheets will only support the .large detent so you don't need to use the presentationDetents view modifier when you want your sheet to only support the view's full height.

Formatting dates in Swift using Date.FormatStyle on iOS 15

Working with dates isn’t easy. And showing them to your users in the correct locale hasn’t always been easy either. With iOS 15, Apple introduced a new way to convert Date objects from and to String. This new way comes in the form of the new Formatter api that replaces DateFormatter.

As any seasoned iOS developer will tell you, DateFormatter objects are expensive to create, and therefor kind of tedious to manage correctly. With the new Formatter api, we no longer need to work with DateFormatter. Instead, we can ask a date to format itself based on our requirements in a more performant, easier to use way.

In this post I will show you how you can convert Date objects to String as well as how you can extract a Date from a String.

Converting a Date to a String

The most straightforward way to convert a Date to a String is the following:

let formatted = Date().formatted() // 5/26/2022, 7:52 PM

By default, the formatted() function uses a compact configuration for our String. The way formatted() converts our Date to String takes into account the user’s current locale. For example, if my device was set to be in Dutch, the date would be formatted as 26-5-2022 19:54 which is a more appropriate formatting for the Dutch language.

However, this might not always be what we need. For example, we might want to have our date formatted as May 26 2022, 7:52 PM. We can use the following code to do that:

let formatted = Date().formatted(
    .dateTime
        .day().month(.wide).year()
        .hour().minute()
)

Let’s break this code apart a bit. The formatted function takes an object that conforms to the FormatStyle protocol as its argument. There are various ways for us to create such an object. The FormatStyle protocol has several convenient extensions that can provide us with several different formatters.

For example, when sending a Date to a server, we’ll often need to send our dates as ISO8601 compliant strings. Before I explain the code you just saw, I want to show you how to grab an ISO8601 compliant string from the current Date.

let formatted = Date().formatted(.iso8601) // 2022-05-26T18:06:55Z

Neat, huh?

Okay, back to the example from before. The .datetime formatter is used as a basis for our custom formatting. We can call various functions on the object that’s returned by the .datetime static property to select the information that we want to show.

Some of these properties, like the month, can be configured to specify how they should be formatted. In the case of .month, we can choose the .wide formatting to spell out the full month name. We could use .narrow to abbreviate the month down to a single letter, or we could use one of the other options to represent the month in different ways.

If you omit a property, like for example .year(), our formatted date will omit the year that’s embedded in the Date. And again, the underlying formatter will always automatically respect your user’s locale which is really convenient.

Another way to format the date is to by specifying how you want the date and time to be formatted respectively:

let formatted = Date().formatted(date: .complete, time: .standard) // Thursday, May 26, 2022, 8:15:28 PM

The above provides a very verbose formatted string. We can make a more compact one using the following settings:

let formatted = Date().formatted(date: .abbreviated, time: .shortened) // May 26, 2022, 8:16 PM

It’s even possible to omit the date or time entirely by using the .omitted option:

let formatted = Date().formatted(date: .abbreviated, time: .omitted) // May 26, 2022

There are tons of different combinations you could come up with so I highly recommend you explore this api some more to get a sense of how flexible it really is.

Creating a Date from a String

Converting String to Date is slightly less convenient than going from a Date to a String but it’s still not too bad. Here’s how you could cover the common case of converting an ISO8601 compliant string to a Date:

let string = "2022-05-26T18:06:55Z"
let expectedFormat = Date.ISO8601FormatStyle()
let date = try! Date(string, strategy: expectedFormat)

We make use of the Date initializer that takes a string and a formatting strategy that’s used to parse the string.

We can also use and configure an instance of FormatStyle to specify the components that we expect to be present in our date string and let the system parse it using the user’s locale:

let string = "May 26, 2022, 8:30 PM"
let expectedFormat = Date.FormatStyle()
    .month().year().day()
    .hour().minute()
let date = try! Date(string, strategy: expectedFormat)

The order of our date components doesn’t matter; they will automatically be rearranged to match the user’s locale. This is super powerful, but it does mean that we can’t use this to parse dates on devices that use a different locale than the one that matches the string’s locale. The best locale agnostic date string is ISO8601 so if you have control over the date strings that you’ll parse, make sure you use ISO8601 when possible.

Summary

In this short article, you learned how you can use iOS 15’s FormatStyle to work format Date objects. You saw how to go from Date to String, and the other way around. While FormatStyle is more convenient than DateFormatter, it’s iOS 15 only. So if you’re still supporting iOS 14 you’ll want to make sure to check out DateFormatter too.

Closures in Swift explained

Closures are a powerful programming concept that enable many different programming patterns. However, for lots of beginning programmers, closures can be tricky to use and understand. This is especially true when closures are used in an asynchronous context. For example, when they’re used as completion handlers or if they’re passed around in an app so they can be called later.

In this post, I will explain what closures are in Swift, how they work, and most importantly I will show you various examples of closures with increasing complexity. By the end of this post you will understand everything you need to know to make effective use of closures in your app.

If by the end of this post the concept of closures is still a little foreign, that’s okay. In that case, I would recommend you take a day or two to process what you’ve read and come back to this post later; closures are by no means a simple topic and it’s okay if you need to read this post more than once to fully grasp the concept.

Understanding what closures are in programming

Closures are by no means a unique concept to Swift. For example, languages like JavaScript and Python both have support for closures. A closure in programming is defined as an executable body of code that captures (or closes over) values from its environment. In some ways, you can think of a closure as an instance of a function that has access to a specific context and/or captures specific values and can be called later.

Let’s look at a code example to see what I mean by that:

var counter = 1

let myClosure = {
    print(counter)
}

myClosure() // prints 1
counter += 1
myClosure() // prints 2

In the above example, I’ve created a simple closure called myClosure that prints the current value of my counter property. Because counter and the closure exist in the same scope, my closure can read the current value of counter. If I want to run my closure, I call it like a function myClosure(). This will cause the code to print the current value of counter.

We can also capture the value of counter at the time the closure is created as follows:

var counter = 1

let myClosure = { [counter] in
    print(counter)
}

myClosure() // prints 1
counter += 1
myClosure() // prints 1

By writing [counter] in we create a capture list that takes a snapshot of the current value of counter which will cause us to ignore any changes that are made to counter. We’ll take a closer look at capture lists in a bit; for now, this is all you need to know about them.

The nice thing about a closure is that you can do all kinds of stuff with it. For example, you can pass a closure to a function:

var counter = 1

let myClosure = {
    print(counter)
}

func performClosure(_ closure: () -> Void) {
    closure()
}

performClosure(myClosure)

This example is a little silly, but it shows how closures are “portable”. In other words, they can be passed around and called whenever needed.

In Swift, a closure that’s passed to a function can be created inline:

performClosure({
    print(counter)
})

Or, when using Swift’s trailing closure syntax:

performClosure {
    print(counter)
}

Both of these examples produce the exact same output as when we passed myClosure to performClosure.

Another common use for closures comes from functional programming. In functional programming functionality is modeled using functions rather than types. This means that creating an object that will add some number to an input isn’t done by creating a struct like this:

struct AddingObject {
    let amountToAdd: Int

    func addTo(_ input: Int) -> Int {
        return input + amountToAdd
    }
}

Instead, the same functionality would be achieved through a function that returns a closure:

func addingFunction(amountToAdd: Int) -> (Int) -> Int {
    let closure = { input in 
        return amountToAdd + input 
    }

    return closure
}

The above function is just a plain function that returns an object of type (Int) -> Int. In other words, it returns a closure that takes one Int as an argument, and returns another Int. Inside of addingFunction(amountToAdd:), I create a closure that takes one argument called input, and this closure returns amountToAdd + input. So it captures whatever value we passed for amountToAdd, and it adds that value to input. The created closure is then returned.

This means that we can create a function that always adds 3 to its input as follows:

let addThree = addingFunction(amountToAdd: 3)
let output = addThree(5)
print(output) // prints 8

In this example we took a function that takes two values (the base 3, and the value 5) and we converted it into two separately callable functions. One that takes the base and returns a closure, and one that we call with the value. The act of doing this is called currying. I won’t go into currying more for now, but if you’re interested in learning more, you know what to Google for.

The nice thing in this example is that the closure that’s created and returned by addingFunction can be called as often and with as many inputs as we’d like. The result will always be that the number three is added to our input.

While not all syntax might be obvious just yet, the principle of closures should slowly start to make sense by now. A closure is nothing more than a piece of code that captures values from its scope, and can be called at a later time. Throughout this post I’ll show you more examples of closures in Swift so don’t worry if this description still is a little abstract.

Before we get to the examples, let’s take a closer look at closure syntax in Swift.

Understanding closure syntax in Swift

While closures aren’t unique to Swift, I figured it’s best to talk about syntax in a separate section. You already saw that the type of a closure in Swift uses the following shape:

() -> Void

This looks very similar to a function:

func myFunction() -> Void

Except in Swift, we don’t write -> Void after every function because every function that doesn’t return anything implicitly returns Void. For closures, we must always write down the return type even when the closure doesn’t return anything.

Another way that some folks like to write closures that return nothing is as follows:

() -> ()

Instead of -> Void or "returns Void", this type specifies -> () or "returns empty tuple". In Swift, Void is a type alias for an empty tuple. I personally prefer to write -> Void at all times because it communicates my intent much clearer, and it's generally less confusing to see () -> Void rather than () -> (). Throughout this post you won't see -> () again, but I did want to mention it since a friend pointed out that it would be useful.

A closure that takes arguments is defined as follows:

let myClosure: (Int, Int) -> Void

This code defines a closure that takes two Int arguments and returns Void. If we were to write this closure, it would look as follows:

let myClosure: (Int, Int) -> Void = { int1, int2 in 
  print(int1, int2)
}

In closures, we always write the argument names followed by in to signal the start of your closure body. The example above is actually a shorthand syntax for the following:

let myClosure: (Int, Int) -> Void = { (int1: Int, int2: Int) in 
  print(int1, int2)
}

Or if we want to be even more verbose:

let myClosure: (Int, Int) -> Void = { (int1: Int, int2: Int) -> Void in 
  print(int1, int2)
}

Luckily, Swift is smart enough to understand the types of our arguments and it’s smart enough to infer the return type of our closure from the closure body so we don’t need to specify all that. However, sometimes the compiler gets confused and you’ll find that adding types to your code can help.

With this in mind, the code from earlier should now make more sense:

func addingFunction(amountToAdd: Int) -> (Int) -> Int {
    let closure = { input in 
        return amountToAdd + input 
    }

    return closure
}

While func addingFunction(amountToAdd: Int) -> (Int) -> Int might look a little weird you now know that addingFunction returns (Int) -> Int. In other words a closure that takes an Int as its argument, and returns another Int.

Earlier, I mentioned that Swift has capture lists. Let’s take a look at those next.

Understanding capture lists in closures

A capture list in Swift specifies values to capture from its environment. Whenever you want to use a value that is not defined in the same scope as the scope that your closure is created in, or if you want to use a value that is owned by a class, you need to be explicit about it by writing a capture list.

Let’s go back to a slightly different version of our first example:

class ExampleClass {
    var counter = 1

    lazy var closure: () -> Void = {
        print(counter)
    } 
}

This code will not compile due to the following error:

Reference to property `counter` requires explicit use of `self` to make capture semantics explicit.

In other words, we’re trying to capture a property that belongs to a class and we need to be explicit in how we capture this property.

One way is to follow the example and capture self:

class ExampleClass {
    var counter = 1

    lazy var closure: () -> Void = { [self] in
        print(counter)
    } 
}

A capture list is written using brackets and contains all the values that you want to capture. Capture lists are written before argument lists.

This example has an issue because it strongly captures self. This means that self has a reference to the closure, and the closure has a strong reference to self. We can fix this in two ways:

  1. We capture self weakly
  2. We capture counter directly

In this case, the first approach is probably what we want:

class ExampleClass {
    var counter = 1

    lazy var closure: () -> Void = { [weak self] in
        guard let self = self else {
            return
        }
        print(self.counter)
    } 
}

let instance = ExampleClass()
instance.closure() // prints 1
instance.counter += 1
instance.closure() // prints 2

Note that inside of the closure I use Swift’s regular guard let syntax to unwrap self.

If I go for the second approach and capture counter, the code would look as follows:

class ExampleClass {
    var counter = 1

    lazy var closure: () -> Void = { [counter] in
        print(counter)
    } 
}

let instance = ExampleClass()
instance.closure() // prints 1
instance.counter += 1
instance.closure() // prints 1

The closure itself looks a little cleaner now, but the value of counter is captured when the lazy var closure is accessed for the first time. This means that the closure will capture whatever the value of counter is at that time. If we increment the counter before accessing the closure, the printed value will be the incremented value:

let instance = ExampleClass()
instance.counter += 1
instance.closure() // prints 2
instance.closure() // prints 2

It’s not very common to actually want to capture a value rather than self in a closure but it’s possible. The caveat to keep in mind is that a capture list will capture the current value of the captured value. In the case of self this means capturing a pointer to the instance of the class you’re working with rather than the values in the class itself.

For that reason, the example that used weak self to avoid a retain cycle did read the latest value of counter.

If you want to learn more about weak self, take a look at this post that I wrote earlier.

Next up, some real-world examples of closures in Swift that you may have seen at some point.

Higher order functions and closures

While this section title sounds really fancy, a higher order function is basically just a function that takes another function. Or in other words, a function that takes a closure as one of its arguments.

If you think this is probably an uncommon pattern in Swift, how does this look?

let strings = [1, 2, 3].map { int in 
    return "Value \(int)"
}

There’s a very good chance that you’ve written something similar before without knowing that map is a higher order function, and that you were passing it a closure. The closure that you pass to map takes a value from your array, and it returns a new value. The map function’s signature looks as follows:

func map<T>(_ transform: (Self.Element) throws -> T) rethrows -> [T]

Ignoring the generics, you can see that map takes the following closure: (Self.Element) throws -> T this should look familiar. Note that closures can throw just like functions can. And the way a closure is marked as throwing is exactly the same as it is for functions.

The map function immediately executes the closure it receives. Another example of such a function is DispatchQueue.async:

DispatchQueue.main.async {
    print("do something")
}

One of the available async function overloads on DispatchQueue is defined as follows:

func async(execute: () -> Void)

As you can see, it’s “just” a function that takes a closure; nothing special.

Defining your own function that takes a closure is fairly straightforward as you’ve seen earlier:

func performClosure(_ closure: () -> Void) {
    closure()
}

Sometimes, a function that takes a closure will store this closure or pass it elsewhere. These closures are marked with @escaping because they escape the scope that they were initially passed to. To learn more about @escaping closures, take a look at this post.

In short, whenever you want to pass a closure that you received to another function, or if you want to store your closure so it can be called later (for example, as a completion handler) you need to mark it as @escaping.

With that said, let’s see how we can use closures to inject functionality into an object.

Storing closures so they can be used later

Often when we’re writing code, we want to be able to inject some kind of abstraction or object that allows us to decouple certain aspects of our code. For example, a networking object might be able to construct URLRequests, but you might have another object that handles authentication tokens and setting the relevant authorization headers on a URLRequest.

You could inject an entire object into your Networking object, but you could also inject a closure that authenticates a URLRequest:

struct Networking {
    let authenticateRequest: (URLRequest) -> URLRequest

    func buildFeedRequest() -> URLRequest {
        let url = URL(string: "https://donnywals.com/feed")!
        let request = URLRequest(url: url)
        let authenticatedRequest = authenticateRequest(request)

        return authenticatedRequest
    }
}

The nice thing about is that you can swap out, or mock, your authentication logic without needing to mock an entire object (nor do you need a protocol with this approach).

The generated initializer for Networking looks as follows:

init(authenticateRequest: @escaping (URLRequest) -> URLRequest) {
    self.authenticateRequest = authenticateRequest
}

Notice how authenticateRequest is an @escaping closure because we store it in our struct which means that the closure outlives the scope of the initializer it’s passed to.

In your app code, you could have a TokenManager object that retrieves a token, and you can then use that token to set the authorization header on your request:

let tokenManager = TokenManager()
let networking = Networking(authenticateRequest: { urlRequest in 
    let token = tokenManager.fetchToken()
    var request = urlRequest
    request.setValue("Bearer \(token)", forHTTPHeaderField: "Authorization")
    return request
})

let feedRequest = networking.buildFeedRequest()
print(feedRequest.value(forHTTPHeaderField: "Authorization")) // a token

What’s cool about this code is that the closure that we pass to Networking captures the tokenManager instance so we can use it inside of the closure body. We can ask the token manager for its current token, and we can return a fully configured request from our closure.

In this example, the closure is injected as a function that can be called whenever we need to authenticate a request. The closure can be called as often as needed, and its body will be run every time we do. Just like a function is run every time you call it.

As you can see in the example, the authenticateRequest is called from within buildFeedRequest to create an authenticated URLRequest.

Storing closures and calling them later is a very powerful pattern but beware of retain cycles. Whenever an @escaping closure captures its owner strongly, you’re almost always creating a retain cycle that should be solved by weakly capturing self (since in most cases self is the owner of the closure).

When you combine what you’ve already learned, you can start reasoning about closures that are called asynchronously, for example as completion handlers.

Closures and asynchronous tasks

Before Swift had async/await, a lot of asynchronous APIs would communicate their results back in the form of completion handlers. A completion handler is nothing more than a regular closure that’s called to indicate that some piece of work has completed or produced a result.

This pattern is important because in a codebase without async/await, an asynchronous function returns before it produces a result. A common example of this is using URLSession to fetch data:

URLSession.shared.dataTask(with: feedRequest) { data, response, error in 
    // this closure is called when the data task completes
}.resume()

The completion handler that you pass to the dataTask function (in this case via trailing closure syntax) is called once the data task completes. This could take a few milliseconds, but it could also take much longer.

Because our closure is called at a later time, a completion handler like this one is always defined as @escapingbecause it escapes the scope that it was passed to.

What’s interesting is that asynchronous code is inherently complex to reason about. This is especially true when this asynchronous code uses completion handlers. However, knowing that completion handlers are just regular closures that are called once the work is done can really simplify your mental model of them.

So what does defining your own function that takes a completion handler look like then? Let’s look at a simple example:

func doSomethingSlow(_ completion: @escaping (Int) -> Void) {
    DispatchQueue.global().async {
        completion(42)
    }
}

Notice how in the above example we don’t actually store the completion closure. However, it is marked as @escaping. The reason for this is that we call the closure from another closure. This other closure is a new scope which means that it escapes the scope of our doSomethingSlow function.

If you’re not sure whether your closure should be escaping or not, just try and compile your code. The compiler will automatically detect when your non-escaping closure is, in fact, escaping and should be marked as such.

Summary

Wow! You’ve learned a lot in this post. Even though closures are a complex topic, I hope that this post has helped you understand them that much better. The more you use closures, and the more you expose yourself to them, the more confident you will feel about them. In fact, I’m sure that you’re already getting lots of exposure to closures but you just might not be consciously aware of it. For example, if you’re writing SwiftUI you’re using closures to specify the contents of your VStacks, HStacks, your Button actions, and more.

If you feel like closures didn’t quite click for you just yet, I recommend that you come back to this post in a few days. This isn’t an easy topic, and it might take a little while for it to sink in. Once the concept clicks, you’ll find yourself writing closures that take other closures while returning more closures in no time. After all, closures can be passed around, held onto, and executed whenever you feel like it.

Feel free to reach out to me on Twitter if you have any questions about this post. I’d love to find out what I could improve to make this the best guide to closures in Swift.

Debugging Network Traffic With Proxyman

Disclaimer: This post is not sponsored by Proxyman, nor am I affiliated with Proxyman in any way. I pay for my license myself, and this post is simply written as a guide to learning more about a tool that I find very important in the iOS Developer toolbox.

Networking is an essential part of modern iOS applications. Most apps I’ve worked have some kind of networking component. Sometimes the networking layer involves user authentication, token refresh flows, and more. Other times, I’ll simply need to hit one or two endpoints to fetch new data or configuration files for my app.

When this all works well, everything is great. But when I notice that things don’t work quite as expected, it’s time to start digging in and debug my network calls. The most simple method would be to convert the data that I’ve fetched from the server to a String and printing it. However, a large response will be hard to read in Xcode’s console so you might have to paste it elsewhere, like in a JSON validator.

When the response you receive is wrong, or not quite what you expected, you’ll want to take a look at the data you’ve sent to the server to make sure you’re not sending it bad data. Doing this isn’t always trivial. Especially when you’re dealing with setting HTTP headers and/or multipart form requests.

In this post, I will show you how you can gain insight into the requests that your app sends to the server as well as see the responses that the server sends to your app. To do this, we’ll use he app Proxyman.

💡 Tip: I’ve written a similar post to this one about Charles Proxy that you can read here. Over time I’ve come to prefer Proxyman for debugging because it’s a nicer app and it’s just a bit easier to set up.

Installing and configuring Proxyman

To use Proxyman, you must first download and install it. You can do this right here on their website. The download for Proxyman is free, and the free version of the app is perfectly usable to explore and learn about debugging your app through a proxy. However, Proxyman isn’t a free app and if you want to use all its features you’ll need to purchase a license. Luckily, a single license is valid forever and entitles you to a year of free updates. After that you can continue the last version that became available during the year, or buy a new license for another year of updates.

Once you’ve downloaded Proxyman, install it by opening the dmg and dragging the app to your Applications folder.

When you first launch Proxyman, it will prompt you for some setup steps and eventually Proxyman will want to install a helper tool. You can safely accept all of Proxyman’s defaults and install the helper tool.

Proxyman helper tool prompt

After setting everything up, you should immediately see network traffic appear in Proxyman’s main window. This is all of the traffic that your Mac is sending and receiving in real-time. This means that you can see any app or website’s network traffic in Proxyman.

When you click on one of the requests, you can see some details about the request. Like for example the request headers, body, and more. You can also see the response for a given request.

There is a caveat though; if the request is performed over HTTPS you won’t see anything just yet.

In the screenshot below, I’ve selected all traffic made by the Proxyman app in the left hand sidebar, and I’ve selected one of the requests in the main section to see more details. Because the request is made using HTTPS, I need to explicitly enable SSL proxying for either a specific host, or all requests made by, in this case, the Proxyman app. Once enabled, re-executing these requests would allow me to inspect their contents.

Proxyman main window

When you first allow SSL proxying for either a domain or an app, you will be prompted to install the Proxyman root certificate. Proxyman can do this automatically for you which is quite convenient. You will be prompted for your admin password so that Proxyman can update your settings and allow SSL proxying.

After enabling SSL proxying, you can select any request and repeat it to make sure that you can now inspect your request and the server’s response. Note that repeating a request isn’t always a valid thing to do so the server you’re hitting might give you an error response; this isn’t something you did wrong with your setup, if you can see the error code everything is working as intended.

Repeat Request in Proxyman

With Proxyman set up, let’s see how we can use it for our apps.

Using Proxyman with the simulator

In order to see the iOS simulator’s traffic appear in Proxyman, you’ll need to install the Proxyman certificates in the simulator. You can do this by selecting Certificates -> Install Certificate on iOS -> Simulators.... This will automatically add the needed certificates to your active iOS simulators so make sure the simulator you want to debug with is active.

Using Proxyman with the simulator

After installing the certificate, you need to reboot your simulator. Once you’ve done this, you can re-run your app and you should start seeing your simulator’s network traffic appear. If you haven’t enabled SSL proxying for the hosts you’re hitting yet, you might have to do this first as you’ve seen earlier.

Inspecting your networking traffic is done in the bottom section of the Proxyman window. On the left side you can see the request you’re sending to the server. You can inspect headers, the request body, query parameters, and anything else you might need.

On the right side of the window you can see the server’s response body and headers.

Proxyman request and response

Being able to have real-time detailed insights into the exact request and responses you’re dealing with is extremely convenient. What’s even more convenient is that you can use Proxyman on a physical device too, allowing you to connect your device to Proxyman on your mac whenever you need to quickly check what your app is doing; even for production builds!

Using Proxyman with a real device

To run Proxyman on a real device, there are a couple of things you’ll need to do. Luckily, Proxyman provides really good instructions in the Mac app.

Start by selecting Certificate -> Install Certificate on iOS -> Physical Devices....

Menu option for proxyman on real device

This will open a window with instructions that you should follow to set up Proxyman for your device.

Proxyman on device instructions

You only need to go through all of these steps once. When you’ve set up your device, all you need to do to start a debugging session is to launch Proxyman on your Mac, connect your iOS device to the network that your Mac is on, and set up the proxy settings for your device in your WiFi settings.

Sharing Proxyman logs with others

One of the main selling points of using a proxy to debug networking isn’t that it’s convenient for developers to validate the request and responses they’re creating and receiving in their apps. In my opinion one of the key selling points of Proxyman is the fact that anybody can install it to capture network traffic.

This means that your QA team can run their device through Proxyman to capture an app’s networking traffic, and include a log of network calls made by the app along with a bug report. This is extremely valuable because it makes troubleshooting network related issues infinitely easier. Having a detailed overview of network calls is so much better than “I just keep getting an unknown error”.

Furthermore, when you’re sure that you’re sending your backend the right thing but the response you’re getting is malformed, or not what you expected, you can easily get Proxyman to export a cURL command that you can send to your backend engineers to help them figure out what’s wrong.

To export a collection of requests you can select them in the main window and right click. Then select Export to see the various export options that are available. You’ll typically want to export as Proxyman Log but if the receiver of your log doesn’t have Proxyman, Charles, Postman, or another format might be more useful.

Export batch of requests

If you just want to export a cURL for a single request you can select the request you want a cURL for, right click, and select Copy cURL. This will get you a cURL request that anybody can run to repeat the request that you’re debugging.

Copy curl menu option

Sending a log or a cURL along with any bug report you have is a really good practice in my opinion. Not only does it improve the quality of your reports, it also makes the lives of your fellow engineers, and backend engineers a lot easier because they’ll have much better insights into what the app is doing with regards to networking.

In addition to capturing iOS device traffic through the Mac app, you can also capture traffic directly on your iOS device with the Proxyman for iOS app. The app can be downloaded through the App Store, and it allows you to quickly start a debugging session right on your iOS device. This can be incredibly useful when you’re not near a Mac but see some weird behavior in your app that you want to explore later. I don’t use the iOS app a lot, but I wanted to mention it anyway.

In summary

In today's tip, you learned how you can use Proxyman to inspect and debug your app’s networking traffic. Being able to debug network calls is an essential skill in the toolbox of any iOS developer in my opinion. Or more broadly speaking, anybody that’s involved in the process of building and testing apps should know how to run an app through a proxy like Proxyman to gain much better insights into an app’s networking traffic, and to build much better bug reports.

This post is merely an introduction to Proxyman, it can do a lot more than just show you request / response pairs. For example, it also allows you to throttle network speeds for specific hosts, and it even allows you to replace requests and responses with local files so you can override what your app sends and/or receives when needed for debugging.

For now, I wish you happy debugging sessions and don't hesitate to shoot me a message on Twitter if you have any questions about debugging your network calls.

The difference between checked and unsafe continuations in Swift

When you’re writing a conversion layer to transform your callback based code into code that supports async/await in Swift, you’ll typically find yourself using continuations. A continuation is a closure that you can call with the result of your asynchronous work. You have the option to pass it the output of your work, an object that conforms to Error, or you can pass it a Result.

In this post, I won’t go in-depth on showing you how to convert your callback based code to async/await (you can refer to this post if you’re interested in learning more). Instead, I’d like to explain the difference between a checked and unsafe continuation in this short post.

If you’ve worked with continuations before, you may have noticed that there are four methods that you can use to create a continuation:

  • withCheckedThrowingContinuation
  • withCheckedContinuation
  • withUnsafeThrowingContinuation
  • withUnsafeContinuation

The main thing that should stand out here is that you have the option of creating a “checked” continuation or an “unsafe” continuation. Your gut might tell you to always use the checked version because the unsafe one sounds... well... unsafe.

To figure out whether this is correct, let’s take a look at what we get with a checked continuation first.

Understanding what a checked continuation does

A checked continuation in Swift is a continuation closure that you can call with the outcome of a traditional asynchronous function that doesn’t yet use async/await, typically one with a callback closure.

This might look a bit as follows:

func validToken(_ completion: @escaping (Result<Token, Error>) -> Void) {
  // eventually calls the completion closure
}

func validTokenFromCompletion() async throws -> Token {
    return try await withCheckedThrowingContinuation { continuation in
        validToken { result in
            continuation.resume(with: result)
        }
    }
}

The code above is a very simple example of bridging the traditional validToken method into the async/await world with a continuation.

There are a couple of rules for using a continuation that you need to keep in mind:

  • You should only call the continuation’s resume once. No more, no less. Calling the resume function twice is a developer error and can lead to undefined behavior.
  • You’re responsible for retaining the continuation and calling resume on it to continue your code. Not resuming your continuation means that withCheckedThrowingContinuation will never throw an error or return a value. In other words, your code will be await-ing forever.

If you fail to do either of the two points above, that’s a developer mistake and you should fix that. Luckily, a checked continuation performs some checks to ensure that:

  • You only call resume once
  • The continuation passed to you is retained in your closure

If either of these checks fail, your app will crash with a descriptive error message to tell you what’s wrong.

Of course, there’s some overhead in performing these checks (although this overhead isn’t enormous). To get rid of this overhead, we can make use of an unsafe continuation.

Is it important that you get rid of this overhead? No, in by far the most situations I highly doubt that the overhead of checked continuations is noticeable in your apps. That said, if you do find a reason to get rid of your checked continuation in favor of an unsafe one, it’s important that you understand what an unsafe continuation does exactly.

Understanding what an unsafe continuation does

In short, an unsafe continuation works in the exact same way as a checked one, with the same rules, except it doesn’t check that you adhere to the rules. This means that mistakes will not be caught early, and you won’t get a clear description of what’s wrong in your crash log.

Instead, an unsafe closure just runs and it might crash or perform other undefined behavior when you break the rules.

That’s really all there is to it for an unsafe continuation, it doesn’t add any functionality, it simply removes all correctness checks that a checked continuation does.

Choosing between a checked and an unsafe continuation

The Swift team recommends that we always make use of checked continuations during development, at least until we’ve verified the correctness of our implementation. Once we know our code is correct and our checked continuation doesn’t throw up any warnings at runtime, it’s safe (enough) to switch to an unsafe continuation if you’d like.

Personally, I prefer to use checked continuations even when I know my implementation is correct. This allows me to continue working on my code, and to make changes, without having to remember to switch back and forth between checked and unsafe continuations.

Of course, there is some overhead involved with checked continuations and if you feel like you might benefit from using an unsafe continuation, you should always profile this first and make sure that this switch is actually providing you with a performance benefit. Making your code less safe based on assumptions is never a great idea. Personally, I have yet to find a reason to favor an unsafe continuation over a checked one.

Wrapping existing asynchronous code in async/await in Swift

Swift's async/await feature significantly enhances the readability of asynchronous code for iOS 13 and later versions. For new projects, it enables us to craft more expressive and easily understandable asynchronous code, which closely resembles synchronous code. However, adopting async/await may require substantial modifications in existing codebases, especially if their asynchronous API relies heavily on completion handler functions.

Fortunately, Swift offers built-in mechanisms that allow us to create a lightweight wrapper around traditional asynchronous code, facilitating its transition into the async/await paradigm. In this post, I'll demonstrate how to convert callback-based asynchronous code into functions compatible with async/await, using Swift's async keyword.

Converting a Callback-Based Function to Async/Await

Callback-based functions vary in structure, but typically resemble the following example:

func validToken(_ completion: @escaping (Result<Token, Error>) -> Void) {
    // Function body...
}

The validToken(_:) function above is a simplified example, taking a completion closure and using it at various points to return the outcome of fetching a valid token.

Tip: To understand more about @escaping closures, check out this post on @escaping in Swift.

To adapt our validToken function for async/await, we create an async throws version returning a Token. The method signature becomes cleaner:

func validToken() async throws -> Token {
    // ...
}

The challenge lies in integrating the existing callback-based validToken with our new async version. We achieve this through a feature known as continuations. Swift provides several types of continuations:

  • withCheckedThrowingContinuation
  • withCheckedContinuation
  • withUnsafeThrowingContinuation
  • withUnsafeContinuation

These continuations exist in checked and unsafe variants, and in throwing and non-throwing forms. For an in-depth comparison, refer to my post that compares checked and unsafe in great detail.

Here’s the revised validToken function using a checked continuation:

func validToken() async throws -> Token {
    return try await withCheckedThrowingContinuation { continuation in
        // Implementation...
    }
}

This function uses withCheckedThrowingContinuation to bridge our callback-based validToken with the async version. The continuation object, created within the function, must be used to resume execution, or the method will remain indefinitely suspended.

The callback-based validToken is invoked immediately, and once resume is called, the async validToken resumes execution. Since the Result type can contain an Error, we handle both success and failure cases accordingly.

The Swift team has simplified this pattern by introducing a version of resume that accepts a Result object:

func validToken() async throws -> Token {
    return try await withCheckedThrowingContinuation { continuation in
        validToken { result in
            continuation.resume(with: result)
        }
    }
}

This approach is more streamlined and elegant.

Remember two crucial points when working with continuations:

  1. A continuation can only be resumed once.
  2. It's your responsibility to call resume within the continuation closure; failure to do so will leave the function awaiting indefinitely.

Despite minor differences (like error handling), all four with*Continuation functions follow these same fundamental rules.

Summary

This post illustrated how to transform a callback-based function into an async function using continuations. You learned about the different types of continuations and their applications.

Continuations are an excellent tool for gradually integrating async/await into your existing codebase without a complete overhaul. I've personally used them to transition large code segments into async/await gradually, allowing for intermediate layers that support async/await in, say, view models and networking, without needing a full rewrite upfront.

In conclusion, continuations offer a straightforward and elegant solution for converting existing callback-based functions into async/await compatible ones.