Solving “reference to var myVariable is not concurrency-safe because it involves shared mutable state” in Swift

Once you start migrating to the Swift 6 language mode, you'll most likely turn on strict concurrency first. Once you've done this there will be several warings and errors that you'll encounter and these errors can be confusing at times.

I'll start by saying that having a solid understanding of actors, sendable, and data races is a huge advantage when you want to adopt the Swift 6 language mode. Pretty much all of the warnings you'll get in strict concurrency mode will tell you about potential issues related to running code concurrently. For an in-depth understanding of actors, sendability and data races I highly recommend that you take a look at my Swift Concurrency course which will get you access to a series of videos, exercises, and my Practical Swift Concurrency book with a single purchase.

WIth that out of the way, let's take a look at the following warning that you might encounter in your project:

reference to var myVariable is not concurrency-safe because it involves shared mutable state

There are multiple reasons for this warning to pop up in Xcode. For example, the code below would cause Xcode to warn us:

// Var 'myVariable' is not concurrency-safe because it is nonisolated global shared mutable state; this is an error in the Swift 6 language mode
var myVariable = UUID()

func randomCharacter() async -> Character {
    myVariable = UUID()
    return myVariable.uuidString.randomElement() ?? "1"
}

The following code makes myVariable a static var which results in the same warning being shown:

struct CharacterMaker {
    // Var 'myVariable' is not concurrency-safe because it is nonisolated global shared mutable state; this is an error in the Swift 6 language mode
    static var myVariable = UUID()

    static func randomCharacter() async -> Character {
        myVariable = UUID()
        return myVariable.uuidString.randomElement() ?? "1"
    }
}

The Swift compiler considers any globally accessible var to be unsafe from a concurrency point of view. The reason for that is that nothing is preventing us from making multiple calls to randomCharacter concurrently which would result in a data race on myVariable. We'd end up with multiple read and write operations at the same time.

To fix this, myVariable should either be moved into an actor or be isolated to a global actor.

For example, you could isolate myVariable to @MainActor like this:

// with a global variable
@MainActor
var myVariable = UUID()

// or as a static property
struct CharacterMaker {
    @MainActor
    static var myVariable = UUID()
    // ...
}

The downside of this is, of course, that we need to be on the main actor to interact with the variable. You can work around this by defining your own (empty) global actor which will ensure that our accesses are on the global executor instead of the main actor:

@globalActor
actor GlobalIsolator {
  static let shared = GlobalIsolator()
}

@GlobalIsolator
var myVariable = UUID()

// or as a static property
struct CharacterMaker {
    @GlobalIsolator
    static var myVariable = UUID()
    // ...
}

This makes accessing myVariable a bit less convenient because you'll need to place yourself on the GlobalIsolator actor when interacting with myVariable:

@GlobalIsolator
static func randomCharacter() async -> Character {
    myVariable = UUID()
    return myVariable.uuidString.randomElement() ?? "1"
}

In some cases you'll know that even though the compiler doesn't like your shared mutable state, you know that it's fine due to the way your code is structured.

If that's the case, and you're absolutely 100% sure that you won't have any issues related to your shared mutable state, you can use nonisolated(unsafe) on your variable to tell the compiler that the lack of isolation is intentional and that you're aware of its data safety issues:

// with a global variable
nonisolated(unsafe) var myVariable = UUID()

// or as a static property
struct CharacterMaker {
    nonisolated(unsafe) static var myVariable = UUID()
    // ...
}

You should only use nonisolated(unsafe) as a last-resort solution because the compiler will no longer be able to help you detect possible data races around myVariable.

Solving “Converting non-sendable function value may introduce data races” in Swift

Once you start migrating to the Swift 6 language mode, you'll most likely turn on strict concurrency first. Once you've done this there will be several warings and errors that you'll encounter and these errors can be confusing at times.

I'll start by saying that having a solid understanding of actors, sendable, and data races is a huge advantage when you want to adopt the Swift 6 language mode. Pretty much all of the warnings you'll get in strict concurrency mode will tell you about potential issues related to running code concurrently. For an in-depth understanding of actors, sendability and data races I highly recommend that you take a look at my Swift Concurrency course which will get you access to a series of videos, exercises, and my Practical Swift Concurrency book with a single purchase.

WIth that out of the way, let's take a look at the following warning that you might encounter in your project:

Converting non-sendable function value may introduce data races

Usually the warning is a bit more detailed, for example in a project I worked on this was the full warning:

Converting non-sendable function value to '@Sendable (Data?, URLResponse?, (any Error)?) -> Void' may introduce data races

This warning (or error in the Swift 6 language mode) tells you that you're trying to pass a non-sendable closure or function to a place that expects something that's @Sendable. For convenience I will only use the term closure but this applies equally to functions.

Consider a function that's defined as follows:

func performNetworkCall(_ completion: @escaping @Sendable (Data?, URLResponse?, (any Error)?) -> Void) {
    // ...
}

This function should be called with a closure that's @Sendable to make sure that we're not introducting data races in our code. When we try and call this function with a closure that's not @Sendable the compiler will complain:

var notSendable: (Data?, URLResponse?, (any Error?)) -> Void = { data, response, error in 
    // ...
}

// Converting non-sendable function value to '@Sendable (Data?, URLResponse?, (any Error)?) -> Void' may introduce data races
performNetworkCall(notSendable)

The compiler is unable to guarantee that our closure is safe to be called in a different actor, task, or other isolation context. So it tells us that we need to fix this.

Usually, the fix for this error is to mark your function or closure as @Sendable:

var notSendable: @Sendable (Data?, URLResponse?, (any Error?)) -> Void = { data, response, error in 
    // ...
}

Now the compiler knows that we intend on our closure to be Sendable and it will perform checks to make sure that it is. We're now also allowed to pass this closure to the performNetworkCall method that you saw earlier.

If you'd like to learn more about Sendable and @Sendable check out my course or read a summary of the topic right here.

What are Optionals in Swift?

In an earlier article, I explained how variables are defined in Swift using let and var. Both constants (let) and variables (var) in Swift always have a type; it's what makes Swift a strongly typed language.

For example, we could define a String variable like this:

// the compiler will know myString is a String
var myString = "Hello, world"

// we're explicitly telling the compiler that myString2 is a String
var myString2: String = "Hello, world"

This way of defining variables makes a lot of sense when it's possible to immediately assign a value to our variable.

However, sometimes you'll write code where it's not possible to assign a value to your variable immediately. Or you're working with functions that may or may not be able to return a valid value.

In Swift, we call values that can distiguish betwene having a value and not having a value an Optional. Before we dig too deeply into how we work with optionals, let's explore the difference between "no value" and "default" value so that we understand exactly why optionals exist in the first place.

If you prefer to learn through video instead of text, check out this video on my YouTube channel

The difference between a default value and no value

In programming, working with a concept called null or as Swift calls it nil will generally mean that a variable or a function's return value can be "nothing". There's a lot of technical baggage surrounding the terminology but in order to establish a good working knowledge, we won't dig into that too deeply.

The important thing to understand here is that defining an empty String like this: var myString = "" defines a String with a default value. The value is empty but the var myString is holding on to some data that will represent an empty String. Often this is a perfectly fine choice.

Now let's consider a different example where a default value would be a lot harder to define.

var theUser: User = ???

Our User object can't be created without input from other sources. And this input might not be present at that time that we define our variable. We'll need a way to define this var theUser with no data rather than a default value.

A real world analogy you might think of is the following. When you sit down at a cafe for some drinks, you will initially have no glasses or cups on your table. As a result, your waiter will know that you haven't been served anything at all so they'll know to go over and hand you a menu, introduce themselves and see whether they can take any orders. Once you've been served you might have some empty glasses on your table. The waiter will now know to ask to refill or take a different order.

This is a demonstration of how no value (no glass on the table) and an empty value (empty glasses on the table) can have significant differences in meaning and they can't always be used interchangeably.

In Swift, we express the ability of a property having no value rather than a default value by defining an optional User object:

var theUser: User?

The ? after our User tells the compiler that var theUser will either contain a value of type User or it will hold nothing at all (we call this nil).

It's nice to know that the ? is a more convenient to write the following:

var theUser: Optional<User>

While the two ways of defining theUser do the same thing, it's best practice to write var theUser: User?. It's easier to read and faster to write.

Note that all types in Swift can be written as an optional. For example, if you're defining a String that might need to be initialized as "no value" you could write: var theString: String?.

The main difference between "no value" and "default value" is often whether there's any semantic meaning to pointing at nothing or pointing to a default value. For example, an optional Bool (Bool?) almost never makes sense; in most scenarios you will be able to pick a sensible default value that's safe to use. In other cases, something being empty or missing could indicate that input from the user is required, or that you need to fetch data from an external source and it's not possible or reasonable to provide a default value.

Now that you know how to write optional properties, let's see how optionals are used in Swift.

Using optionals in your code

Once you've defined an optional value in Swift, it's important that we handle the possibility of a value being nil as well as the value being non-nil. Swift is pretty strict about this so optionals aren't used in the same way as you would use normal variables or constants.

For example, if we consider the theUser variable from earlier, we can't read the name from this property like this:

var theUser: User?

// Value of optional type 'User?' must be unwrapped to refer to member 'name' of wrapped base type 'User'
print(theUser.name)

The Swift compiler will tell us that we need to "unwrap" value of optional type User? in order to access its member name. This is the compiler's way of telling us that theUser may or may not be nil so we need to handle both scenarios.

Let's take a look at severals ways in which we can "unwrap" our optional.

Unwrapping with if let

If we're writing code where we want to only execute a part of our script or function in case the value isn't nil, we can use something called an if let unwrap. Here's what that looks like:

var theUser: User?

// somewhere else in the code...
if let userValue = theUser {
  print(userValue.name)
} else {
  print("the user is nil")
}

This if let attempts to read theUser and we assign it to a constant. This constant is then made available inside of the if's body where we know that userValue is of type User. Outside of our if body we won't be able to access userValue; it's only made available inside of the if. As needed, we can provide an else to handle scenarios where theUser is nil.

Note that the code above could be simplified a bit. Swift allows us to use something called a shadow variable (variable of the same name) for theUser which would change the if let as follows:

var theUser: User?

// somewhere else in the code...
if let theUser {
  print(theUser.name)
} else {
  print("the user is nil")
}

Note that theUser inside of the if body is not the same variable as theUser outside of the if body; it's a different property with the same name. For that reason, theUser inside of the if body is of type User and outside of the if body it's User?. This feature of Swift is nice when you're familiar with optionals but I find that sometimes it's better to provide a different name so that it's clear when you're using your unwrapped property or when you're using your optional property.

Unwrapping optionals with guard let

While if let is great for usage inside of code where it doesn't matter that much whether a value is or isn't nil, you sometimes want to make sure that a value isn't nil at the start of a function. With if let this would generally mean that you write an if let at the start of your function and then write the whole function body inside of your if let:

func performWork() {
  if let unwrappedUser = theUser {
    // do the work
  }
}

This works but it can lead to a lot of nested code. For scenarios where you only wish to proceed in your function if a value is not nil, you can use guard let instead:

func performWork() {
  guard let unwrappedUser = theUser else {
    return
  }

// do the work
// unwrappedUser is available to all code that comes after the guard
}

A guard allows us to ensure that our user has a value and that the unwrapped value is available to all code that comes after the guard. When we're using a guard we must provide an else clause that exits the current scope. Usually this means that we put a return there in order to bail out of the function early.

Unwrapping multiple properties

Both if let and guard let allow us to unwrap multiple properties at once. This is done using a comma separated list:

if let unwrappedUser = theUser, let file = getFile() {
  // we have access to `unwrappedUser` and `file`
}

The syntax for guard let is the same but requires the else:

guard let unwrappedUser = theUser, let file = getFile() else {
  return
}

  // we have access to `unwrappedUser` and `file`

Note that writing your code like this will require all unwraps to succeed. If either our user or file would be nil in the example above, the if body wouldn't be executed and our guard would enter its else condition.

Reading through optional chaining

When you're working with an optional and you'd like to get access to a property that's defined on your object, you could write an if let and then access the property you're interested in. You saw this earlier with User and its name property:

if let theUser {
  print(theUser.name)
}

If we know that we're only interested in the name property we can use a technique called optional chaining to immediately access the name property and assign that to the property we're writing the if let for instead.

Here's what that looks like

if let userName = theUser?.name {
  print(userName)
}

This is very convenient when we're in a situation where we really only care about a single property. If either theUser is nil or (if name is optional) name is nil the if body won't be executed.

We can use this technique to access larger chains of optionals, for example:

if let department = theUser?.department?.name {

}

Both theUser and department are optionals and we can write a chain of access using ? after each optional property. Once any of the properties in the chain is found to be nil the chain ends and the result is nil.

For example, if we just assign the chain from above to a property that property is a String?

// department is String?
let department = theUser?.department?.name

The name on the department property doesn't have to be a String? but because we're using optional chaining we'll get a nil value if either theUser or department is nil.

This leads me to one last method that I'd recommend for working with and that's using the nil coalescing operator.

Unwrapping optionals using nil coalescing

For any optional in Swift, we can provide a default value inline of where we access it. For example:

let username: String?

let displayName = username ?? ""

The ?? operator in the example above is called the nil coalescing operator and we can use it to provide a default value that's used in case the value we're trying to access is nil.

This is particularly useful when you need to provide values to render in a user interface for example.

You can also use this technique in combination with optional chaining:

// department is String
let department = theUser?.department?.name ?? "No department"

Now, let's take a look at one last method to unwrapping that I'm only including for completeness; this approach should only be used as a last resort in my opinion.

Force unwrapping optionals

If you're 100% absolutely sure that an optional value that you're about to access can never be nil, you can force unwrap the optional when accessing it:

print(theUser!.name)

By writing an ! after my optional variable I'm telling the compiler to treat that property as non-optional. This means that I can easily interact with the property without writing an if let, guard let, without optional chaining or without using nil coaslescing. The major downside here is that if my assumptions are wrong and the value is nil after all my program will crash.

For that reason it's almost always preferred to use one of the four safe approaches to unwrapping your optionals instead.

Solving “Capture of non-sendable type in @Sendable closure” in Swift

Once you start migrating to the Swift 6 language mode, you'll most likely turn on strict concurrency first. Once you've done this there will be several warings and errors that you'll encounter and these errors can be confusing at times.

I'll start by saying that having a solid understanding of actors, sendable, and data races is a huge advantage when you want to adopt the Swift 6 language mode. Pretty much all of the warnings you'll get in strict concurrency mode will tell you about potential issues related to running code concurrently. For an in-depth understanding of actors, sendability and data races I highly recommend that you take a look at my Swift Concurrency course which will get you access to a series of videos, exercises, and my Practical Swift Concurrency book with a single purchase.

WIth that out of the way, let's take a look at the following warning that you might encounter in your project:

Capture of non-sendable type in @Sendable closure

This warning tells us that we're capturing and using a property inside of a closure. This closure is marked as @Sendable which means that we should expect this closure to run in a concurrent environment. The Swift compiler warns us that, because this closure will run concurrently, we should make sure that any properties that we capture inside of this closure can safely be used from concurrent code.

In other words, the compiler is telling us that we're risking crashes because we're passing an object that can't be used from multiple tasks to a closure that we should expect to be run from multiple tasks. Or at least we should expect our closure to be transferred from one task to another.

Of course, there's no guarantees that our code will crash. Nor is it guaranteed that our closure will be run from multiple places at the same time. What matters here is that the closure is marked as @Sendable which tells us that we should make sure that anything that's captured inside of the closure is also Sendable.

For a quick overview of Sendability, check out my post on the topic here.

An example of where this warning might occur could look like this:

func run(completed: @escaping TaskCompletion) {
    guard !metaData.isFinished else {
        DispatchQueue.main.async {
            // Capture of 'completed' with non-sendable type 'TaskCompletion' (aka '(Result<Array<any ScheduledTask>, any Error>) -> ()') in a `@Sendable` closure; this is an error in the Swift 6 language mode
            // Sending 'completed' risks causing data races; this is an error in the Swift 6 language mode
            completed(.failure(TUSClientError.uploadIsAlreadyFinished))
        }
        return
    }

    // ...
}

The compiler is telling us that the completed closure that we're receiving in the run function can't be passed toDispatchQueue.main.async safely. The reason for this is that the run function is assumed to be run in one isolation context, and the closure passed to DispatchQueue.main.async will run in another isolation context. Or, in other words, run and DispatchQueue.main.async might run as part of different tasks or as part of different actors.

To fix this, we need. to make sure that our TaskCompletion closure is @Sendable so the compiler knows that we can safely pass that closure across concurrency boundaries:

// before
typealias TaskCompletion = (Result<[ScheduledTask], Error>) -> ()

// after
typealias TaskCompletion = @Sendable (Result<[ScheduledTask], Error>) -> ()

In most apps, a fix like this will introduce new warnings of the same kind. The reason for this is that because the TaskCompletion closure is now @Sendable, the compiler is going to make sure that every closure passed to our run function doesn't captuire any non-sendable types.

For example, one of the places where I call this run function might look like this:

task.run { [weak self] result in
    // Capture of 'self' with non-sendable type 'Scheduler?' in a `@Sendable` closure; this is an error in the Swift 6 language mode
    guard let self = self else { return }
    // ...
}

Because the closure passed to task.run needs to be @Sendable any captured types also need to be made Sendable.

At this point you'll often find that your refactor is snowballing into something much bigger.

In this case, I need to make Scheduler conform to Sendable and there's two ways for me to do that:

  • Conform Scheduler to Sendable
  • Make Scheduler into an actor

The second option is most likely the best option. Making Scheduler an actor would allow me to have mutable state without data races due to actor isolation. Making the Scheduler conform to Sendable without making it an actor would mean that I have to get rid of all mutable state since classes with mutable state can't be made Sendable.

Using an actor would mean that I can no longer directly access a lot of the state and functions on that actor. It'd be required to start awaiting access which means that a lot of my code has to become async and wrapped in Task objects. The refactor would get out of control real fast that way.

To limit the scope of my refactor it makes sense to introduce a third, temporary option:

  • Conform Scheduler to Sendable using the unchecked attribute

For this specific case I have in mind, I know that Scheduler was written to be thread-safe. This means that it's totally safe to work with Scheduler from multiple tasks, threads, and queues. However, this safety was implemented using old mechanisms like DispatchQueue. As a result, the compiler won't just accept my claim that Scheduler is Sendable.

By applying @unchecked Sendable on this class the compiler will accept that Scheduler is Sendable and I can continue my refactor.

Once I'm ready to convert Scheduler to an actor I can remove the @unchecked Sendable, change my class to an actor and continue updating my code and resolving warnings. This is great because it means I don't have to jump down rabbit hole after rabbit hole which would result in a refactor that gets way out of hand and becomes almost impossible to manage correctly.

Solving “Reference to captured var in concurrently-executing code” in Swift

Once you start migrating to the Swift 6 language mode, you'll most likely turn on strict concurrency first. Once you've done this there will be several warings and errors that you'll encounter and these errors can be confusing at times.

I'll start by saying that having a solid understanding of actors, sendable, and data races is a huge advantage when you want to adopt the Swift 6 language mode. Pretty much all of the warnings you'll get in strict concurrency mode will tell you about potential issues related to running code concurrently. For an in-depth understanding of actors, sendability and data races I highly recommend that you take a look at my Swift Concurrency course which will get you access to a series of videos, exercises, and my Practical Swift Concurrency book with a single purchase.

WIth that out of the way, let's take a look at the following warning that you might encounter in your project:

Reference to captured var in concurrently-executing code

This warning tells you that you're capturing a variable inside of a body of code that will run asynchornously. For example, the following code will result in this warning:

var task = NetworkTask<Int, URLSessionUploadTask>(
    urlsessionTask: urlSessionTask
)

upload(fromTask: urlSessionTask, metaData: metaData, completion: { result in
    Task {
        await task.sendResult(result) // Reference to captured var 'task' in concurrently-executing code; this is an error in the Swift 6 language mode
    }
})

The task variable that we create a couple of lines earlier is mutable. This means that we can assign a different value to that task at any time and that could result in inconsistencies in our data. For example, if we assign a new value to the task before the closure starts running, we might have captured the old task which could be unexpected.

Since strict concurrency is meant to help us make sure that our code runs as free of surprises as possible, Swift wants us to make sure that we capture a constant value instead. In this case, I'm not mutating task anyway so it's safe to make it a let:

let task = NetworkTask<Int, URLSessionUploadTask>(
    urlsessionTask: urlSessionTask
)

upload(fromTask: urlSessionTask, metaData: metaData, completion: { result in
    Task {
        await task.sendResult(result)
    }
})

This change gets rid of the warning because the compiler now knows for sure that task won't be given a new value at some unexpected time.

Another way to fix this error would be to make in explicit capture in the completion closure that I'm passing. This capture will happen immediately as a let so Swift will know that the captured value will not change unexpectedly.

var task = NetworkTask<Int, URLSessionUploadTask>(
    urlsessionTask: urlSessionTask
)

upload(fromTask: urlSessionTask, metaData: metaData, completion: { [task] result in
    Task {
        await task.sendResult(result.mapError({ $0 as any Error }))
    }
})

Altenatively, you could make an explicit constant capture before your Task runs:

var task = NetworkTask<Int, URLSessionUploadTask>(
    urlsessionTask: urlSessionTask
)

let theTask = task
upload(fromTask: urlSessionTask, metaData: metaData, completion: { result in
    Task {
        await theTask.sendResult(result)
    }
})

This is not as elegant but might be needed in cases where you do want to pass your variable to a piece of concurrently executing code but you also want it to be a mutable property for other objects. It's essentially the exact same thing as making a capture in your completion closure (or directly in the task if there's no extra wrapping closures involved).

When you first encounter this warning it might be immediately obvious why you're seeing this error and how you should fix it. In virtual all cases it means that you need to either change your var to a let or that you need to perform an explicit capture of your variable either by making a shadowing let or through a capture list on the first concurrent bit of code that accesses your variable. In the case of the example in this post that's the completion closure but for you it might be directly on the Task.

Adding values to the SwiftUI environment with Xcode 16’s Entry macro

Adding custom values to SwiftUI’s environment has never been very hard to do to. However, the syntax for doing it is verbose and easy to forget. To refresh your mind, take a look at this post where I explain how to add your own environment values to a SwiftUI view.

To summarize what’s shown in that post; here’s how you add a custom value to the environment using Xcode 15 and earlier:

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

We have to define an environment key, define a default value, and write a getter and setter to retrieve our value from the environment using our key.

This is repetitive, easy to forget, and just annoying to do.

If you prefer learning thorugh video, here's the video to watch:

Luckily, in Xcode 16 we have access to the @Entry macro. This macro allows us to define the exact same environment key like this:

extension EnvironmentValues {
    @Entry var dateFormatter: DateFormatter = {
        let formatter = DateFormatter()
        formatter.locale = Locale(identifier: "en_US_POSIX")
        formatter.dateFormat = "MM/dd/yyyy"
        return formatter
    }()
}

All we have to define now is a variable that’s annotated with @Entry and we’re done.

The property name is used as the environment key so in this case we’d set our date formatter like this:

myView
    .environment(\.dateFormatter, Dateformatter())

I absolutely love this new syntax because it gets rid of all the boilerplate in one go.

And the best part of this macro?

We can use it in projects that target iOS versions older than 18! So as soon as you start developing your project with Xcode 16 you’ll be able to use this macro regardless of your deployment target.

Let and var in Swift explained

Virtually every programming language will have some means to define properties; Swift does too. We have two approaches to defining a property in Swift. We can use a var or a let. The code below shows how we can define a var or a let as a member of a class:

class Member {
  let id: UUID
  var name: String

  init(name: String) {
    self.id = UUID()
    self.name = name
  }
}

This class has two properties. One is a let, the other is a var.

If you're coming from a Javascript background you might expect that there's a third option here; const. That's not the case in Swift. Swift only has let and var and a let in Swift might not be what you think it is.

A var property is a variable. That means that whatever we assign to the var can change over time. For example, when I make an instance of my Member object, I can change the name as needed:

var instance = Member(name: "Donny")
instance.name = "Hello, world!"

And because I defined instance as a var, I'm even able to create a new Member and assign it to my instance variable:

var instance = Member(name: "Donny")
instance.name = "Hello, world!"

instance = Member(name: "Oliver")

We also refer to a var as being mutable. This is another way of saying that the value for this property can change.

A let is the opposite. It's a constant value. This means that once we've assigned a value, we can't change it.

For example, if I define my instance as a let instead of a var I'm no longer allowed to assign a new value to instance:

// notice how intstance is now defined as a let
let instance = Member(name: "Donny")
instance.name = "Hello, world!"

instance = Member(name: "Oliver") // not allowed, instance is a let

Additionally, because my Member defined id as a let, I can't change that either:

let instance = Member(name: "Donny")
instance.id = UUID() // not allowed, id is a let

I can, however still change the name:

let instance = Member(name: "Donny")
instance.name = "Hello, world!"

That's because changing a property on my class instance will propagate as a change to let instance. The class instance assigned to let instance is still the exact same one. We just changed one of the properties.

This changes when we'd make Member a struct:

struct Member {
  let id: UUID
  var name: String

  init(name: String) {
    self.id = UUID()
    self.name = name
  }
}

The properties on Member are the exact same. The only difference is that we've made Member a struct instead of a class.

I won't expand into the difference between structs and classes too much in this post, but it's important to understand that a class is assigned to a variable(var) or constant(let) using its address in memory. So instead of storing the actual class value in our property, we only store the location of our class instance. That's why changing a value on our instance doesn't re-assign to our let instance in the example above.

Structs on the other hand are generally stored by value. This means that when you change a property on a struct, Swift will have to re-assign the new value to the property that's storing your instance. Let's see this in action:

let instance = Member(name: "Donny")
instance.name = "Hello, world!" // this is not allowed because `instance` is immutable

What's happening in the code above is that we've assigned a value to let instance. When we change the name of our instance, Swift has to replace the old value of instance with a new one because it's a struct and structs are stored using their values.

To allow mutating our instance.name, we have to store the instance as a var:

var instance = Member(name: "Donny")
instance.name = "Hello, world!" // this is allowed because `instance` is a variable

Now Swift is able to make a copy of our Member with the updated name and then assign it back to var instance.

We generally like to write our code using let instead of var whenever we can. The fewer properties we can change, the more predictable our code becomes, and the fewer bugs we'll ship. However, a program that never changes any of its properties wouldn't be very interesting because it'd just be a static page. So in those situations where you do need the ability to re-assign or update a property it makes sense to define that property as a var. When in doubt, use let. Then change it to a var when you find that you do have a need to update that specific property later on.

Using PreviewModifier to build a previewing environment

Xcode 16 and iOS 18 come with a feature that allows us to build elaborate preview environments using a new PreviewModifier protocol. This protocol allows us to define objects that can create a single context or environment that’s cached and used across your SwiftUI previews.

This is useful because it means that you could, for example, populate a database with a bunch of mock data that is then used in your previews.

You can also use PreviewModifier to apply specific styling to your previews, to wrap them all in a specific wrapper, and more.

Essentially, they’re a tool that allows you to configure your previews consistently across the board.

Decorating views using PreviewModifier

The PreviewModifier protocol specifies two methods that you can implement:

  • A static makeSharedContext method
  • An instance method called body

The body instance methods is passed the view that’s being previewed and a Context. This context can either be an object that you created in makeSharedContext or Void if you don’t implement makeSharedContext.

For this example, let’s assume that you went ahead and did not implement makeSharedContext. In a situation like that, we can use PreviewModifier to decorate a view for our previews. For example, we could wrap it in another view or apply some styling to it.

I’m pretty sure that you’re more creative than me so I’m just going to go ahead and show you how you would apply a orange background to your previewed view. Yeah, I know… very creative. The point is to show you how to do this so that you can do something much smarter than what I’m describing here.

struct OrangeBackground: PreviewModifier {
    func body(content: Content, context: Void) -> some View {
        content
            .padding()
            .background {
                RoundedRectangle(cornerRadius: 16)
                    .fill(.orange)
            }
    }
}

#Preview(traits: .modifier(OrangeBackground())) {
    Text("Hello, world!")
}

Let’s look at the PreviewModifier first, and then I’ll explain how I applied it to my preview.

The modifier is defined as a struct and I only implemented the body function.

This function is padded Content which is whatever view the #Preview macro is being used on (in this case, Text), and it receives a context. In this case Void because I didn’t make a context.

The content argument can be styled, modified, and wrapped however you need. It’s a view so you can do things like give it a background, transform it, adjust its environment, and much much more. Anything you can do with a view inside of a View body you can do here.

The main difference is that you’re receiving a fully instantiated instance of your view. That means you can’t inject new state or bindings into it or otherwise modify it. You can only apply view modifiers to it.

This brings us to our next feature of PreviewModifier creating a context to provide mocked data and more.

Using PreviewModifier to inject mock data

To inject mock data into your previews through PreviewModifier all you need to do is implement the makeSharedContext method from the PreviewModifier protocol. This method is static and is called once for all your previews. This means that the context that you create in this method is reused for all of your previews.

In practice this is nice because it means you get consistent mock data for your previews without the overhead of recreating this data frequently.

Here’s what a sample implementation for makeSharedContext looks like:

struct MockDataSource {
    // ...
}

struct OrangeBackground: PreviewModifier {
    static func makeSharedContext() async throws -> MockDataSource {
        return MockDataSource()
    }
}

In this case, I’m creating an instance of some data source in my makeSharedContext method. This MockDataSource would hold all mocks and all data for my views which is great.

However, the only way for us to really use that mock data in our view is by adding our data source (or the mocked data) to our previewed view’s environment.

struct OrangeBackground: PreviewModifier {
    static func makeSharedContext() async throws -> MockDataSource {
        return MockDataSource()
    }

    func body(content: Content, context: MockDataSource) -> some View {
        content
            .environment(\.dataSource, context)
    }
}

Since we can’t make a new instance of our content, we can’t inject our mock data source directly into the view through its initializer. The only way we can get the data source to the view is by adding it to the environment.

This is not ideal in my opinion, but the design makes sense.

I’m also pretty sure that Apple designed this API with mocking SwiftData databases in mind and it would work great for that.

On top of having to use the environment, the PreviewModifier only works in projects that target iOS 18 or later. Not a huge problem but it would have been nice if using Xcode 16 was good enough for us to be able to use this handy new API.

Mixing colors in SwiftUI and Xcode 16

SwiftUI in iOS 18 and macOS 15 has gained a new trick; it can mix colors. This means that it’s now possible to take a color and modify it by applying another color to it using a provided percentage.

The video below shows how this works:

Notice how the large rectangle updates its color to be a certain mix of a left and right color.

In the video I use distinct colors but you can also mix with white or black to lighten or darken your color.

One use of color mixing I like a lot is to explore color palettes. Since you can see which colors “fit” between two distinct colors you get to explore color in a way that, to me, is very inspiring.

If you prefer learning through video over learning through text, here's a video that I made a companion for this post:

Here’s the code that allows you to mix two colors in SwiftUI:

let leftColor = Color.pink
let rightColor = Color.blue
let mix = 0.5

// create a rectangle filled with our mixed color
RoundedRectangle(cornerRadius: 16)
    .fill(leftColor.mix(with: rightColor, by: mix, in: .perceptual))
    .frame(width: 100, height: 100)

The API is pretty straightforward. You take a color and you call mix on it. You pass a second color, a mixing value between 0 and 1, and whether you want to interpolate the mixed color in a perceptual color space or using the device color space.

By default, perceptual will be used since that should, in theory, mix colors in a way that makes sense to the human eye and is consistent between different device screens. Mixing based on device color space can yield different results that may or may not be what you’re looking for; I recommend experimenting to see the exact differences.

The mixing value that you provide determines how much of the second color should be mixed into the source color. A value of 0 gets you the original color and a value of 1 replaces the original color entirely with the color you’re mixing in.

If you’re interested in rebuilding the experiment UI from the start of this post, you can grab the code right here:

struct ColorMix: View {
    @State private var leftColor = Color.blue
    @State private var rightColor = Color.pink
    @State private var mix = 0.5

    var body: some View {
        VStack {
            HStack(spacing: 8) {
                ColorPicker("Left", selection: $leftColor)
                    .labelsHidden()
                ColorPicker("Right", selection: $rightColor)
                    .labelsHidden()
            }

            HStack {
                VStack {
                    RoundedRectangle(cornerRadius: 16)
                        .fill(leftColor)
                        .frame(width: 100, height: 100)
                    Text("\((1 - mix), format: .percent.precision(.fractionLength(0...2)))")
                }

                VStack {
                    RoundedRectangle(cornerRadius: 16)
                        .fill(rightColor)
                        .frame(width: 100, height: 100)
                    Text("\(mix, format: .percent.precision(.fractionLength(0...2)))")
                }
            }

            // create a rectangle filled with our mixed color
            RoundedRectangle(cornerRadius: 16)
                .fill(leftColor.mix(with: rightColor, by: mix, in: .perceptual))
                .frame(width: 100, height: 100)

            Slider(value: $mix, in: 0...1)
        }
    }
}

Using iOS 18’s new TabView with a sidebar

In iOS 18, Apple has revamped the way that tab bars look. They used to be positioned at the bottom of the screen with an icon and a text underneath. Starting with iOS 18, tab bars will no longer be displayed in that manner.

Instead, on iPad you will have your tab bar on the top of the screen with text-only items while on iPhone your tab bar will retain its old look.

In addition to changing how a tab bar looks, Apple has also added new behavior to the tab bar; it can expand into a sidebar that contains a more detailed hierarchy of navigation items.

In this post, I’d like to take a look at this feature and in particular I’d like to share some things that I’ve learned about how Apple handles sidebars that contain sectioned content. Consider this post to be both a demonstration of how you can have a TabBar that doubles as a sidebar as well as some tips and tricks that will help you craft a great experience when you choose to adopt a TabBar that can become a sidebar with sections.

Understanding our goal

Now, I could show you the SwiftUI views and view modifiers you need in order to build a sidebar / tabview pair for iPad and I could show you that it works and end this post there. However, that would be a little bit too shortsighted and you might just as well watch Apple’s own content on this topic instead.

What I’d like to show you in this post, is how you can leverage a sectioned sidebar that makes sense and also has a tab bar that actually works well on phones. In this screenshot you can see all the different variants of the tab/sidebar that I want to support.

Our TabView in various configurations

Notice how my tab bar has only a couple of items in it in the compact mode that’s used for a split-screen iPad or iPhone. On my full width iPad display I have a tab bar that contains several elements like “Blog” and “Books”. And when shown as a sidebar, these tab bar items become category headings instead.

Supporting all this is fairly straightforward but it comes with some gotchas that I’d like to outline in this post.

Setting up our TabView and Sections

While we do need to take into account several form factors and write some special code to handle smaller screens we’ll start by building out our large-screen TabView first.

Within a TabView we can define both Tab and TabSection items. A Tab is shown as a tab in the tab view and the sidebar too. In the screenshot above I’ve added Main and Search as Tab in my TabView. You can see that they’re not grouped under any header.

Then there’s Blog, Books, Courses, and more. These are sections that all contain their own list of tabs.

Let’s go right ahead and look at the code that I use to build my hierarchy of tabs and sections. I’ll only include a single TabSection since the code would be pretty long and repetitive otherwise.

var body: some View {
    TabView {
        Tab("Main", systemImage: "house") {
            OverviewView()
        }

        TabSection("Blog") {
            Tab("All topics", systemImage: "pencil") {
                Text("This is the blog page")
            }

            Tab("SwiftUI", systemImage: "swift") {
                Text("SwiftUI topic")
            }

            Tab("Concurrency", systemImage: "timelapse") {
                Text("Concurrency topic")
            }

            Tab("Persistence", systemImage: "swiftdata") {
                Text("Persistence topic")
            }
        }

        // .. more TabSections

        Tab(role: .search) {
            Text("Search the site")
        }
    }
}

If I’d run this code as-is, my TabView would work but user’s won’t be able to toggle it into a sidebar. We’ll fix that in a moment. Let’s look at my hierarchy first.

My top-level Tab objects will always be shown on my tab bar. The Tab(role: .search) that I have here is a special case; that tab will always be shown on the trailing side of my tab bar with a search icon.

My TabSection is an interesting case. In tab bar view, the section’s name will be used as the name for my tab bar item. The view that’s shown to the user when they select this tab bar item is the detail view for the first Tab in the section. So in this case, that’s “All topics”. This is great because “All topics” is an overview page for the section.

TabView on iPad

When running on a small screen however, every Tab is added to the tab bar regardless of their sections. This means that on iPhone, the tab bar is cluttered with all kinds of tab bar items we don’t want.

Here’s what we get when we run on iPhone. Notice that we don’t see the same tab bar items. Instead, every Tab we’ve defined at any level is being listed.

The same TabView on iPhone with way too many tabs

We’ll fix this after we enable sidebar toggling.

Enabling sidebar toggling

To allow users to switch our tab bar into a sidebar, we need to apply the tabViewStyle view modifier to the TabView as follows:

var body: some View {
    TabView {
      // tabs and sections...
    }
    .tabViewStyle(.sidebarAdaptable)
}

By setting the tabViewStyle to sidebarAdaptable, users can now toggle between our tab bar and a sidebar easily.

In sidebar mode, all of our root Tab items are listed first. After that, sections are listed with the section name as headers, and in each section we see the Tab views that we’ve added.

Our app with a sidebar

Switching between a sidebar and tab bar looks pretty good now and it works well.

But for smaller size classes (like phones and split-view iPad) we’ll want to do something else.

Let’s see how we can adapt our TabView to smaller screens.

Adapting the TabView to smaller screens

In SwiftUI, we can gain access to the current size class for our view through the environment. Since our TabView will become a traditional tab bar at the bottom of the screen on compact size classes and be in the new style on regular we can actually change the contents of our TabView based on the size class so that all extra items we had before will be gone if the size class is compact. Here’s what that looks like:

@Environment(\.horizontalSizeClass)
var horizontalSize

var body: some View {
    TabView {
        Tab("Main", systemImage: "house") {
            OverviewView()
        }

        if horizontalSize == .regular {
            TabSection("Blog") {
                Tab("All topics", systemImage: "pencil") {
                    Text("This is the blog page")
                }

                Tab("SwiftUI", systemImage: "swift") {
                    Text("SwiftUI topic")
                }

                Tab("Concurrency", systemImage: "timelapse") {
                    Text("Concurrency topic")
                }

                Tab("Persistence", systemImage: "swiftdata") {
                    Text("Persistence topic")
                }
            }
        } else {
            Tab("Blog", systemImage: "pencil") {
                Text("This is the blog page")
            }
        }

        // repeat for other sections...
    }
}

The code is relatively simple and it’s very effective. We’ll just have different tab items depending on the size class.

If you want to make sure that tab selection is maintained, you can actually reuse the same tag for tabs that represent the same screen in your app.

And that’s it! With this setup you’re ready to support iPhone and iPad while using the new tab bar and sidebar hybrid view.