-1.1 C
New York
Friday, December 6, 2024

Fixing “Seize of non-sendable sort in @Sendable closure” in Swift


Revealed on: August 7, 2024

When you begin migrating to the Swift 6 language mode, you will probably activate strict concurrency first. As soon as you’ve got executed this there can be a number of warings and errors that you will encounter and these errors might be complicated at occasions.

I will begin by saying that having a strong understanding of actors, sendable, and knowledge races is a big benefit while you wish to undertake the Swift 6 language mode. Just about all the warnings you will get in strict concurrency mode will inform you about potential points associated to operating code concurrently. For an in-depth understanding of actors, sendability and knowledge races I extremely advocate that you simply check out my Swift Concurrency course which can get you entry to a collection of movies, workouts, and my Sensible Swift Concurrency ebook with a single buy.

WIth that out of the best way, let’s check out the next warning that you simply would possibly encounter in your mission:

Seize of non-sendable sort in @Sendable closure

This warning tells us that we’re capturing and utilizing a property inside a closure. This closure is marked as @Sendable which implies that we should always count on 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 be sure that any properties that we seize inside 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 count on to be run from a number of duties. Or at the very least we should always count on our closure to be transferred from one activity 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 be sure that something that is captured inside the closure can be Sendable.

For a fast overview of Sendability, take a look at my publish on the subject right here.

An instance of the place this warning would possibly happen might appear like this:

func run(accomplished: @escaping TaskCompletion) {
    guard !metaData.isFinished else {
        DispatchQueue.primary.async {
            // Seize of 'accomplished' with non-sendable sort 'TaskCompletion' (aka '(End result, any Error>) -> ()') in a `@Sendable` closure; that is an error within the Swift 6 language mode
            // Sending 'accomplished' dangers inflicting knowledge 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 perform cannot be handed toDispatchQueue.primary.async safely. The explanation for that is that the run perform is assumed to be run in a single isolation context, and the closure handed to DispatchQueue.primary.async will run in one other isolation context. Or, in different phrases, run and DispatchQueue.primary.async would possibly run as a part of completely different duties or as a part of completely different actors.

To repair this, we’d like. to be sure 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 = (End result<[ScheduledTask], Error>) -> ()

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

In most apps, a repair like it will introduce new warnings of the identical variety. The explanation for that is that as a result of the TaskCompletion closure is now @Sendable, the compiler goes to be sure that each closure handed to our run perform would not captuire any non-sendable varieties.

For instance, one of many locations the place I name this run perform would possibly appear like this:

activity.run { [weak self] end in
    // 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 activity.run must be @Sendable any captured varieties additionally must be made Sendable.

At this level you will usually discover that your refactor is snowballing into one thing a lot larger.

On this case, I have to make Scheduler conform to Sendable and there is two methods for me to try this:

  • Conform Scheduler to Sendable
  • Make Scheduler into an actor

The second choice is probably the best choice. Making Scheduler an actor would permit me to have mutable state with out knowledge races on account of 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 lessons with mutable state cannot be made Sendable.

Utilizing an actor would imply that I can not instantly entry a variety of the state and capabilities on that actor. It would be required to start out awaiting entry which implies that a variety of my code has to develop into async and wrapped in Activity objects. The refactor would get uncontrolled actual quick that means.

To restrict the scope of my refactor it is smart to introduce a 3rd, short-term choice:

  • Conform Scheduler to Sendable utilizing the unchecked attribute

For this particular case I take note of, I do know that Scheduler was written to be thread-safe. Because of this it’s very secure to work with Scheduler from a number of duties, threads, and queues. Nevertheless, this security was carried out utilizing outdated mechanisms like DispatchQueue. In consequence, 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 end in a refactor that will get means out of hand and turns into nearly not possible to handle appropriately.

Related Articles

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Latest Articles