Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Swift Sendable and strict concurrency

Swift Sendable and strict concurrency

The most important change in Swift 6 is turning "concurrency safety" from a convention voluntarily followed by developers into a rule enforced by the compiler.

At the core of these rules is a protocol called Sendable, which answers the same question: can this value safely cross a concurrency boundary and be used by another thread or another actor?

This article starts with data races, then explains Sendable's automatic inference, manual annotation, and the cost of @unchecked Sendable, and finally gives a complete path for migrating from Swift 5 to Swift 6.

Note:The examples on this page are all verified in Swift 6 language mode. When running as a command-line script, you must explicitly add -swift-version 6, otherwise swift The command still compiles under the lenient Swift 5 rules by default, so many errors do not appear.


Data races: the hardest kind of bug to find in concurrency

A data race occurs when two or more threads access the same memory at the same time, with at least one being a write, and no synchronization mechanism.

What makes it frightening is that it "does not necessarily fail": most of the time the result is correct, occasionally it is wrong, or it simply crashes, yet it cannot be reproduced on another machine.

Example

import Foundation

// A mutable reference type with no synchronization protection

final

class

RunoobCounter

{

    var value

=

0

}

func runoobDemo

(

)

{

    let counter

=

RunoobCounter

(

)

    let group

=

DispatchGroup

(

)

   

for

_ in

0

..

<

1000

{

        group.

enter

(

)

        DispatchQueue.

global

(

)

.

async

{

            counter.

value

=

1

 

// Multiple threads writing the same memory at once: a data race

            group.

leave

(

)

       

}

   

}

    group.

wait

(

)

    print

(

counter.

value

)

}

runoobDemo

(

)

The code above gives a different result every run; it may be less than 1000, or it may crash.

The problem is not that the code is "not careful enough", but that the compiler has no way of knowing counter will be shared by multiple threads.

Sendable exists to let the compiler know this: if a value is marked Sendable, it means handing it to another thread is safe.

Data races and race conditions are not the same thing:A data race is the objective fact of "accessing the same memory at the same moment"; a race condition is the logical problem of "the result depends on execution order". Sendable eliminates the former; the latter requires proper synchronization design.


What is the Sendable protocol?

Sendable is a "marker protocol" with no requirements that must be implemented.

A type conforming to Sendable is a promise to the compiler that values of this type can safely be passed across concurrency domains.

It appears in two places: the generic constraint T: Sendable and the closure type @Sendable () -> Void.

The table below lists the Sendable status of common types, which is the basis for understanding all the rules that follow.

Type Is it Sendable? Description
Int、Double、Bool、String Is Value semantics with immutable internals
Array、Dictionary、Set Yes when elements are Sendable Yes when the generic parameter satisfies it
Tuple Yes when all elements are Sendable Inferred element by element
Custom struct, enum Automatically yes when members are Sendable Automatically inferred by the compiler
actor Is Internal state protected by actor isolation
@MainActor-isolated classes Is The entire type is protected by the main actor
Ordinary class No Reference semantics, not automatically inferred
Class with mutable stored properties No Errors even if declared Sendable

The easiest rows to misremember in this table are the last two: structs are inferred automatically, classes are not.


Automatic inference of Sendable

A struct or enum automatically satisfies Sendable as long as all its stored properties are Sendable, with no annotation needed.

Example

import Foundation

// Automatic inference: a struct whose stored properties are all Sendable

struct

RunoobConfig

{

    let site

:

String

    let port

:

Int

}

func check

<

T

:

Sendable

(

_ value

:

T

)

String

{

   

"(type(of: value)) satisfies Sendable"

}

print

(

check

(

RunoobConfig

(

site

:

"www.runoob.com"

, port

:

80

)

)

)

print

(

check

(

42

)

)

print

(

check

(

"RUNOOB"

)

)



RunoobConfig 满足 Sendable

Int 满足 Sendable

String 满足 Sendable

Note that RunoobConfig does not write : Sendable, yet passing it to a generic function with T: Sendable produces no error at all.

Conversely, if even one property does not satisfy it, the whole struct does not satisfy it.

Example

import Foundation

class

RunoobMutable

{

var value

=

0

}

// If a struct contains a non-Sendable property, the whole struct does not satisfy it either

struct

RunoobBad

{

    let box

:

RunoobMutable

}

func check

<

T

:

Sendable

(

_ v

:

T

)

{

print

(

"(type(of: v)) OK"

)

}

check

(

RunoobBad

(

box

:

RunoobMutable

(

)

)

)



error: type 'RunoobBad' does not conform to the 'Sendable' protocol

Enums are inferred layer by layer too; when all associated values are Sendable, the whole enum is Sendable.

Example

import Foundation

// Automatically satisfied when an enum's associated values are all Sendable

enum

RunoobResult

:

Sendable

{

   

case

success

(

String

)

   

case

failure

(

Int

)

}

// A frozen public enum is inferred normally even across modules

@frozen

public

enum

RunoobStatus

:

Sendable

{

   

case

ok

   

case

error

}

let r

=

RunoobResult.

success

(

"RUNOOB"

)

print

(

r

)

print

(

RunoobStatus.

ok

)



success("RUNOOB")

ok

The rules for classes are completely different: even if a class meets the condition "final + all stored properties immutable and Sendable", the compiler stillIt does notdoes not infer automatically and it must be written explicitly.

Example

import Foundation

// final + all stored properties are let with Sendable types, so Sendable can be declared explicitly

final

class

RunoobSite

:

Sendable

{

    let name

:

String

    let url

:

String

    init

(

name

:

String, url

:

String

)

{

        self.

name

=

name

        self.

url

=

url

   

}

}

func runoobCheck

<

T

:

Sendable

(

_ value

:

T

)

{

    print

(

"(type(of: value)) satisfies Sendable"

)

}

runoobCheck

(

RunoobSite

(

name

:

"RUNOOB"

, url

:

"www.runoob.com"

)

)



RunoobSite 满足 Sendable

If a mutable stored property appears in this class, explicitly declaring Sendable is directly rejected by the compiler.

Example

import Foundation

final

class

RunoobSite

:

Sendable

{

    var name

:

String

=

"RUNOOB"

}



error: stored property 'name' of 'Sendable'-conforming class 'RunoobSite' is mutable


Several correct ways to annotate Sendable manually

When a class truly needs to be passed across concurrency domains and has mutable state, the correct approach is to protect the state with a synchronization primitive before declaring Sendable.

Swift 6 provides Mutex in the Synchronization module, which is currently the most recommended approach.

Example

import Foundation

import Synchronization

// Mutex protects the internal state, so this class can safely declare Sendable

final

class

RunoobCounter

:

Sendable

{

   

private

let state

=

Mutex

(

0

)

    func increment

(

)

Int

{

        state.

withLock

{

value in

            value

=

1

           

return

value

       

}

   

}

}

func runoobDemo

(

)

{

    let counter

=

RunoobCounter

(

)

    print

(

counter.

increment

(

)

)

    print

(

counter.

increment

(

)

)

}

runoobDemo

(

)



1

2

A class with only immutable state needs no synchronization after declaring Sendable, because there is nothing that can be corrupted.

Types isolated by a global actor, such as classes marked @MainActor, also automatically satisfy Sendable because all access is forced to be serialized onto the main actor.

Example

import Foundation

@MainActor

final

class

RunoobVM

{

    var count

=

0

}

func check

<

T

:

Sendable

(

_ v

:

T, _ label

:

String

)

{

    print

(

"(label) satisfies Sendable"

)

}

func runoobDemo

(

)

async

{

    let vm

=

await RunoobVM

(

)

    check

(

vm,

"RunoobVM"

)

    check

(

[

1

,

2

,

3

]

,

"[Int]"

)

    check

(

[

"a"

:

"b"

]

,

"[String: String]"

)

}

await runoobDemo

(

)



RunoobVM 满足 Sendable

[Int] 满足 Sendable

[String: String] 满足 Sendable

Another common scenario is global mutable state. Swift 6 does not allow top-level global var to be read or written directly by non-isolated code; the solution is to put it inside a namespace and mark it @MainActor.

Example

import Foundation

// Put global state into an enum namespace, then you can mark it @MainActor

enum

RunoobStore

{

    @MainActor

static

var cache

:

[

String

:

String

]

=

[

:

]

    @MainActor

static

func store

(

_ key

:

String, _ value

:

String

)

{

        cache

[

key

]

=

value

   

}

    @MainActor

static

func value

(

for

key

:

String

)

String

?

{

        cache

[

key

]

   

}

}

func runoobDemo

(

)

async

{

    await RunoobStore.

store

(

"site"

,

"www.runoob.com"

)

    let value

=

await RunoobStore.

value

(

for

:

"site"

)

    print

(

value

??

"nil"

)

}

await runoobDemo

(

)



www.runoob.com


The risks of @unchecked Sendable

Some classes cannot be proven safe by the compiler's rules, but the developer knows what they are doing; in that case you can write @unchecked Sendable.

The meaning of "unchecked" is very direct:Skip the compiler's checks, at your own risk。

Example

import Foundation

// Using a lock to protect internal state is a correct use of @unchecked Sendable

final

class

RunoobCache

:

@unchecked Sendable

{

   

private

let lock

=

NSLock

(

)

   

private

var storage

:

[

String

:

String

]

=

[

:

]

    func store

(

_ key

:

String, _ value

:

String

)

{

        lock.

lock

(

)

        defer

{

lock.

unlock

(

)

}

        storage

[

key

]

=

value

   

}

    func value

(

for

key

:

String

)

String

?

{

        lock.

lock

(

)

        defer

{

lock.

unlock

(

)

}

       

return

storage

[

key

]

   

}

}

let cache

=

RunoobCache

(

)

cache.

store

(

"site"

,

"www.runoob.com"

)

print

(

cache.

value

(

for

:

"site"

)

??

"nil"

)



www.runoob.com

The code above compiles and runs fine, but it is not "proven safe" but rather "declared safe".

The danger is that once @unchecked Sendable is added, the compiler no longer performs any checks on this class, and even mistakes will not be flagged.

Example

import Foundation

// Bad example: no synchronization protection at all, yet the compiler is fooled by @unchecked

final

class

RunoobCounter

:

@unchecked Sendable

{

   

private

var value

=

0

         

// No lock and no actor isolation

    func increment

(

)

{

value

=

1

}

}

This code compiles just as well, but under multiple threads it is a complete data race.

Guiding principle:First try to solve the problem in ways the compiler understands, such as actor, Mutex, and immutable state; only when none of these apply and you have truly protected all mutable state with low-level synchronization primitives should you use @unchecked Sendable. It should be a last resort, not a shortcut for silencing errors.


Strict checking in Swift 6 language mode

Swift 6 mode does not introduce new syntax; instead it upgrades issues that previously gave only warnings into compile-time errors.

The most typical kind is an @Sendable closure capturing a non-Sendable value.

Example

import Foundation

class

RunoobBox

{

    var value

=

0

}

func runoobPerform

(

_ body

:

@Sendable

(

)

Void

)

{

    body

(

)

}

func runoobDemo

(

)

{

    let box

=

RunoobBox

(

)

    runoobPerform

{

        box.

value

=

1

 

// The closure may run across threads and captures a non-Sendable box

   

}

    print

(

box.

value

)

}

runoobDemo

(

)



error: capture of 'box' with non-Sendable type 'RunoobBox' in a '@Sendable' closure

The same code produces no errors at all in Swift 5 mode, which is exactly why many people suddenly "get a bunch of errors" when upgrading.

The second common kind of error is global mutable state being accessed by non-isolated code.

Example

import Foundation

var runoobGlobalCounter

=

0

 

// A top-level var is isolated to the main actor by default

func runoobDemo

(

)

{

         

// An ordinary function is non-isolated

    runoobGlobalCounter

=

1

    print

(

runoobGlobalCounter

)

}

runoobDemo

(

)



error: main actor-isolated var 'runoobGlobalCounter' can not be mutated from a nonisolated context

If this global variable is truly used only in a single thread, you can use nonisolated(unsafe) to explicitly turn off the check.

Example

import Foundation

// nonisolated(unsafe): explicitly declaring "I know there is a risk here"

nonisolated

(

unsafe

)

var runoobGlobalCounter

=

0

func runoobDemo

(

)

{

    runoobGlobalCounter

=

1

    print

(

runoobGlobalCounter

)

}

runoobDemo

(

)



1

There are three ways to enable Swift 6 mode; just choose according to your scenario.

Scenario How to Enable
Xcode project In Build Settings, set Swift Language Version to Swift 6
Swift Package Write in Package.swift swiftLanguageModes: [.v6]
Command line swiftc -swift-version 6

The path for migrating from Swift 5 to Swift 6

The official guidance does not require doing it all at once. In Swift 5 mode there is a -strict-concurrency option that lets you tighten the checks gradually in three levels.

Level Check intensity Typical use
minimal Only checks the most obvious explicit concurrency annotations The default for legacy projects, virtually unnoticeable
targeted Checks code that uses concurrency APIs The first step of migration, with less noise
complete Full checking, with issues reported as warnings The final step of migration, preparing for the mode switch

You can think of these three levels as a gradual process of "look at warnings first, then fix the code, and finally turn on errors".



# Gradually tighten checks in Swift 5 mode, issues first appear as warnings

swiftc -swift-version 5 -strict-concurrency=targeted Runoob.swift

swiftc -swift-version 5 -strict-concurrency=complete Runoob.swift



# After all warnings are handled, switch to Swift 6 mode

swiftc -swift-version 6 Runoob.swift

When migrating, following the order below is usually much faster than fixing errors one by one.

Step Action Description
1 Turn on targeted checking First resolve issues related to concurrency APIs
2 Annotate UI-related types with @MainActor Eliminate a large number of main-thread isolation issues at once
3 Replace hand-written locks with actors Let the compiler understand synchronization boundaries
4 Add @preconcurrency to legacy cross-module APIs Temporarily suppress errors from dependencies that have not yet been adapted
5 Turn on complete checking and clean up remaining warnings Prepare for switching to Swift 6 mode
6 Switch to Swift 6 mode All warnings become errors

When a dependent third-party library has not yet been adapted, you can add @preconcurrency before the import to have the compiler use the module under Swift 5 rules, buying yourself some time.

The syntax is @preconcurrency import ModuleName. For example, if the project depends on a networking library RunoobLegacyKit that has not yet been adapted to strict concurrency, import it this way first, then remove the prefix once the dependency is upgraded.


Common questions

Do structs always conform to Sendable

Not necessarily. Only when itsAllstored properties are all Sendable does it conform.

As long as one property is a plain class, the whole struct does not conform, and this judgment is recursive.

Why is an actor inherently Sendable

Because an actor's internal state can only be accessed via await, and the compiler serializes it automatically.

Therefore it is safe to hand an actor instance to another thread, since it handles isolation itself.

Can @unchecked Sendable be added freely

No. It is a switch that turns off checking; once added, the compiler no longer verifies anything.

It is only correct when all mutable state is protected by locks, queues, or atomic operations.

What is the difference between Task and Task.detached regarding Sendable

Task { } inherits the current actor context, so when created in the main actor it still runs on the main actor.

Task.detached { } does not inherit any context, so the values it captures must genuinely conform to Sendable, and the checks are stricter.

Why does my Swift 5 project show none of these errors

Because the default check level in Swift 5 language mode is minimal, and the vast majority of concurrency issues are not reported.

You need to explicitly add -strict-concurrency=complete, or switch directly to Swift 6 mode, to see the full diagnostics.