Revealed on: August 7, 2024
When you begin migrating to the Swift 6 language mode, you may almost definitely activate strict concurrency first. As soon as you’ve got performed this there can be a number of warings and errors that you will encounter and these errors may be complicated at occasions.
I am going to begin by saying that having a strong understanding of actors, sendable, and information races is a big benefit if you need to undertake the Swift 6 language mode. Just about all the warnings you may get in strict concurrency mode will let you know about potential points associated to working code concurrently. For an in-depth understanding of actors, sendability and information races I extremely advocate that you simply check out my Swift Concurrency course which is able to get you entry to a collection of movies, workouts, and my Sensible Swift Concurrency e-book with a single buy.
WIth that out of the best way, let’s check out the next warning that you simply may encounter in your mission:
Seize of non-sendable sort in @Sendable closure
This warning tells us that we’re capturing and utilizing a property within a closure. This closure is marked as @Sendable
which signifies that we should always anticipate this closure to run in a concurrent setting. The Swift compiler warns us that, as a result of this closure will run concurrently, we should always ensure that any properties that we seize within this closure can safely be used from concurrent code.
In different phrases, the compiler is telling us that we’re risking crashes as a result of we’re passing an object that may’t be used from a number of duties to a closure that we should always anticipate to be run from a number of duties. Or at the very least we should always anticipate our closure to be transferred from one job to a different.
In fact, there is not any ensures that our code will crash. Neither is it assured that our closure can be run from a number of locations on the similar time. What issues right here is that the closure is marked as @Sendable
which tells us that we should always ensure that something that is captured within the closure can also be Sendable
.
For a fast overview of Sendability, try my publish on the subject right here.
An instance of the place this warning may happen may appear like this:
func run(accomplished: @escaping TaskCompletion) {
guard !metaData.isFinished else {
DispatchQueue.major.async {
// Seize of 'accomplished' with non-sendable sort 'TaskCompletion' (aka '(Outcome, any Error>) -> ()') in a `@Sendable` closure; that is an error within the Swift 6 language mode
// Sending 'accomplished' dangers inflicting information races; that is an error within the Swift 6 language mode
accomplished(.failure(TUSClientError.uploadIsAlreadyFinished))
}
return
}
// ...
}
The compiler is telling us that the accomplished
closure that we’re receiving within the run
operate cannot be handed toDispatchQueue.major.async
safely. The rationale for that is that the run
operate is assumed to be run in a single isolation context, and the closure handed to DispatchQueue.major.async
will run in one other isolation context. Or, in different phrases, run
and DispatchQueue.major.async
may run as a part of totally different duties or as a part of totally different actors.
To repair this, we’d like. to ensure that our TaskCompletion
closure is @Sendable
so the compiler is aware of that we are able to safely move that closure throughout concurrency boundaries:
// earlier than
typealias TaskCompletion = (Outcome<[ScheduledTask], Error>) -> ()
// after
typealias TaskCompletion = @Sendable (Outcome<[ScheduledTask], Error>) -> ()
In most apps, a repair like this can introduce new warnings of the identical type. The rationale for that is that as a result of the TaskCompletion
closure is now @Sendable
, the compiler goes to ensure that each closure handed to our run
operate does not captuire any non-sendable sorts.
For instance, one of many locations the place I name this run
operate may appear like this:
job.run { [weak self] lead to
// Seize of 'self' with non-sendable sort 'Scheduler?' in a `@Sendable` closure; that is an error within the Swift 6 language mode
guard let self = self else { return }
// ...
}
As a result of the closure handed to job.run
must be @Sendable
any captured sorts additionally have to be made Sendable.
At this level you may usually discover that your refactor is snowballing into one thing a lot greater.
On this case, I must make Scheduler
conform to Sendable
and there is two methods for me to do this:
- Conform
Scheduler
toSendable
- Make
Scheduler
into anactor
The second possibility is almost definitely the most suitable choice. Making Scheduler
an actor would permit me to have mutable state with out information races attributable to actor isolation. Making the Scheduler
conform to Sendable
with out making it an actor would imply that I’ve to do away with all mutable state since courses with mutable state cannot be made Sendable
.
Utilizing an actor
would imply that I can not immediately entry a number of the state and capabilities on that actor. It might be required to begin awaiting entry which signifies that a number of my code has to turn out to be async
and wrapped in Activity
objects. The refactor would get uncontrolled actual quick that approach.
To restrict the scope of my refactor it is smart to introduce a 3rd, short-term possibility:
- Conform
Scheduler
toSendable
utilizing theunchecked
attribute
For this particular case I keep in mind, I do know that Scheduler
was written to be thread-safe. Which means that it’s very protected to work with Scheduler
from a number of duties, threads, and queues. Nevertheless, this security was applied utilizing outdated mechanisms like DispatchQueue
. Because of this, the compiler will not simply settle for my declare that Scheduler
is Sendable
.
By making use of @unchecked Sendable
on this class the compiler will settle for that Scheduler
is Sendable
and I can proceed my refactor.
As soon as I am able to convert Scheduler
to an actor
I can take away the @unchecked Sendable
, change my class
to an actor
and proceed updating my code and resolving warnings. That is nice as a result of it means I haven’t got to leap down rabbit gap after rabbit gap which might lead to a refactor that will get approach out of hand and turns into nearly unattainable to handle appropriately.