├── .editorconfig ├── .gitattributes ├── .gitignore ├── CODEOWNERS ├── CONTRIBUTING.md ├── Guide.docc ├── CommonProblems.md ├── CompleteChecking.md ├── DataRaceSafety.md ├── IncrementalAdoption.md ├── Info.plist ├── LibraryEvolution.md ├── MigrationGuide.md ├── MigrationStrategy.md ├── RuntimeBehavior.md ├── SourceCompatibility.md └── Swift6Mode.md ├── LICENSE.txt ├── Package.swift ├── README.md ├── Sources ├── Examples │ ├── Boundaries.swift │ ├── ConformanceMismatches.swift │ ├── DispatchQueue+PendingWork.swift │ ├── Globals.swift │ ├── IncrementalMigration.swift │ ├── PreconcurrencyImport.swift │ └── main.swift ├── Library │ └── Library.swift ├── ObjCLibrary │ ├── JPKJetPack.h │ ├── JPKJetPack.m │ ├── ObjCLibrary.h │ └── ObjCLibrary.m ├── Swift5Examples └── Swift6Examples ├── Tests └── Library │ ├── LibraryTests.swift │ └── LibraryXCTests.swift └── bin ├── local.sh ├── publish.sh └── redirects └── index.html /.editorconfig: -------------------------------------------------------------------------------- 1 | root = true 2 | 3 | [*] 4 | indent_style = space 5 | indent_size = 4 6 | end_of_line = lf 7 | charset = utf-8 8 | trim_trailing_whitespace = true 9 | insert_final_newline = true 10 | -------------------------------------------------------------------------------- /.gitattributes: -------------------------------------------------------------------------------- 1 | *.md linguist-detectable=true 2 | *.md linguist-documentation=false 3 | *.md diff=markdown 4 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .DS_Store 2 | .docc-build 3 | .swiftpm 4 | /.build 5 | /Package.resolved 6 | /Guide.docc/header.html 7 | /migration-guide 8 | -------------------------------------------------------------------------------- /CODEOWNERS: -------------------------------------------------------------------------------- 1 | # Lines starting with '#' are comments. 2 | # Each line is a case-sensitive file pattern followed by one or more owners. 3 | # Order is important. The last matching pattern has the most precedence. 4 | # More information: https://docs.github.com/en/articles/about-code-owners 5 | # 6 | # Please mirror the repository's file hierarchy in case-sensitive lexicographic 7 | # order. 8 | 9 | * @hborla @mattmassicotte @shahmishal @ktoso 10 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing to the Swift Migration Guide 2 | 3 | ## Welcome the Swift community! 4 | 5 | Contributions to the Swift project are welcomed and encouraged! 6 | Please see the [Contributing to Swift guide](https://www.swift.org/contributing/) 7 | and check out the structure of the community. 8 | 9 | To be a truly great community, Swift needs to welcome developers from all walks 10 | of life, with different backgrounds, and with a wide range of experience. A 11 | diverse and friendly community will have more great ideas, more unique 12 | perspectives, and produce more great code. We will work diligently to make the 13 | Swift community welcoming to everyone. 14 | 15 | To give clarity of what is expected of our members, Swift has adopted the code 16 | of conduct defined by the Contributor Covenant. This document is used across 17 | many open source communities, and we think it articulates our values well. 18 | For more, see the [Code of Conduct](https://www.swift.org/code-of-conduct/). 19 | 20 | ## Contributing to swift-migration-guide 21 | 22 | ### How you can help 23 | 24 | We would love your contributions in the form of: 25 | - Filing issues to cover specific code patterns or additional sections of the 26 | guide 27 | - Opening pull requests to improve existing content or add new content 28 | - Reviewing others' pull requests for clarity and correctness of writing 29 | and code examples 30 | 31 | ### Submitting Issues and Pull Requests 32 | 33 | #### Issues 34 | 35 | File bugs about the content using the [issues page][bugs] on Github. 36 | 37 | #### Opening pull requests 38 | 39 | To create a pull request, fork this repository, push your change to 40 | a branch, and open a pull request against the `main` branch. 41 | 42 | #### Build and test 43 | 44 | Run `docc preview Guide.docc` in this repository's root directory. 45 | 46 | After running DocC, open the link that `docc` outputs to display a local 47 | preview in your browser. 48 | 49 | > Note: 50 | > 51 | > If you installed DocC by downloading a toolchain from Swift.org, 52 | > `docc` is located in `usr/bin/`, 53 | > relative to the installation path of the toolchain. 54 | > Make sure your shell's `PATH` environment variable 55 | > includes that directory. 56 | > 57 | > If you installed DocC by downloading Xcode, 58 | > use `xcrun docc` instead. 59 | 60 | #### Running CI 61 | 62 | Pull requests must pass CI testing via `@swift-ci please test` before the change is merged. 63 | 64 | ### Getting your PR reviewed 65 | 66 | Reviewers will be tagged automatically when you open a pull request. You may 67 | be asked to make changes during code review. When you are ready, use the 68 | request re-review feature of github or mention the reviewers by name in a comment. 69 | 70 | [bugs]: https://github.com/apple/swift-migration-guide/issues -------------------------------------------------------------------------------- /Guide.docc/CommonProblems.md: -------------------------------------------------------------------------------- 1 | # Common Compiler Errors 2 | 3 | Identify, understand, and address common problems you can encounter while 4 | working with Swift concurrency. 5 | 6 | The data isolation guarantees made by the compiler affect all Swift code. 7 | This means complete concurrency checking can surface latent issues, 8 | even in Swift 5 code that doesn't use any concurrency language features 9 | directly. 10 | With the Swift 6 language mode enabled, some of these potential issues 11 | can also become errors. 12 | 13 | After enabling complete checking, many projects can contain a large 14 | number of warnings and errors. 15 | _Don't_ get overwhelmed! 16 | Most of these can be tracked down to a much smaller set of root causes. 17 | And these causes, frequently, are a result of common patterns which aren't 18 | just easy to fix, but can also be very instructive while learning about 19 | Swift's concurrency system. 20 | 21 | ## Unsafe Global and Static Variables 22 | 23 | Global state, including static variables, are accessible from anywhere in a 24 | program. 25 | This visibility makes them particularly susceptible to concurrent access. 26 | Before data-race safety, global variable patterns relied on programmers 27 | carefully accessing global state in ways that avoided data-races 28 | without any help from the compiler. 29 | 30 | > Experiment: These code examples are available in package form. 31 | Try them out yourself in [Globals.swift][Globals]. 32 | 33 | [Globals]: https://github.com/apple/swift-migration-guide/blob/main/Sources/Examples/Globals.swift 34 | 35 | ### Sendable Types 36 | 37 | ```swift 38 | var supportedStyleCount = 42 39 | ``` 40 | 41 | Here, we have defined a global variable. 42 | The global variable is both non-isolated _and_ mutable from any 43 | isolation domain. Compiling the above code in Swift 6 mode 44 | produces an error message: 45 | 46 | ``` 47 | 1 | var supportedStyleCount = 42 48 | | |- error: global variable 'supportedStyleCount' is not concurrency-safe because it is non-isolated global shared mutable state 49 | | |- note: convert 'supportedStyleCount' to a 'let' constant to make the shared state immutable 50 | | |- note: restrict 'supportedStyleCount' to the main actor if it will only be accessed from the main thread 51 | | |- note: unsafely mark 'supportedStyleCount' as concurrency-safe if all accesses are protected by an external synchronization mechanism 52 | 2 | 53 | ``` 54 | 55 | Two functions with different isolation domains accessing this 56 | variable risks a data race. In the following code, `printSupportedStyles()` 57 | could be running on the main actor concurrently with a call to 58 | `addNewStyle()` from another isolation domain: 59 | 60 | ```swift 61 | @MainActor 62 | func printSupportedStyles() { 63 | print("Supported styles: ", supportedStyleCount) 64 | } 65 | 66 | func addNewStyle() { 67 | let style = Style() 68 | 69 | supportedStyleCount += 1 70 | 71 | storeStyle(style) 72 | } 73 | ``` 74 | 75 | One way to address the problem is by changing the variable's isolation. 76 | 77 | ```swift 78 | @MainActor 79 | var supportedStyleCount = 42 80 | ``` 81 | 82 | The variable remains mutable, but has been isolated to a global actor. 83 | All accesses can now only happen in one isolation domain, and the synchronous 84 | access within `addNewStyle` would be invalid at compile time. 85 | 86 | If the variable is meant to be constant and is never mutated, 87 | a straight-forward solution is to express this to the compiler. 88 | By changing the `var` to a `let`, the compiler can statically 89 | disallow mutation, guaranteeing safe read-only access. 90 | 91 | ```swift 92 | let supportedStyleCount = 42 93 | ``` 94 | 95 | A global value can also be expressed with a computed property. 96 | If such property consistently returns the same constant value, 97 | this is semantically equivalent to a `let` constant as far as 98 | observable values/effects are concerned: 99 | 100 | ```swift 101 | var supportedStyleCount: Int { 102 | 42 103 | } 104 | ``` 105 | 106 | If there is synchronization in place that protects this variable in a way that 107 | is invisible to the compiler, you can disable all isolation checking for 108 | `supportedStyleCount` using `nonisolated(unsafe)`. 109 | 110 | ```swift 111 | /// This value is only ever accessed while holding `styleLock`. 112 | nonisolated(unsafe) var supportedStyleCount = 42 113 | ``` 114 | 115 | Only use `nonisolated(unsafe)` when you are carefully guarding all access to 116 | the variable with an external synchronization mechanism such as a lock or 117 | dispatch queue. 118 | 119 | ### Non-Sendable Types 120 | 121 | In the above examples, the variable is an `Int`, 122 | a value type that is inherently `Sendable`. 123 | Global _reference_ types present an additional challenge, because they 124 | are typically not `Sendable`. 125 | 126 | ```swift 127 | class WindowStyler { 128 | var background: ColorComponents 129 | 130 | static let defaultStyler = WindowStyler() 131 | } 132 | ``` 133 | 134 | The problem with this `static let` declaration is not related to the 135 | mutability of the variable. 136 | The issue is `WindowStyler` is a non-`Sendable` type, making its internal state 137 | unsafe to share across isolation domains. 138 | 139 | ```swift 140 | func resetDefaultStyle() { 141 | WindowStyler.defaultStyler.background = ColorComponents(red: 1.0, green: 1.0, blue: 1.0) 142 | } 143 | 144 | @MainActor 145 | class StyleStore { 146 | var stylers: [WindowStyler] 147 | 148 | func hasDefaultBackground() -> Bool { 149 | stylers.contains { $0.background == WindowStyler.defaultStyler.background } 150 | } 151 | } 152 | ``` 153 | 154 | Here, we see two functions that could access the internal state of the 155 | `WindowStyler.defaultStyler` concurrently. 156 | The compiler only permits these kinds of cross-isolation accesses with 157 | `Sendable` types. 158 | One option is to isolate the variable to a single domain using a global actor. 159 | Alternatively, it might make sense to add a conformance to `Sendable` 160 | directly. 161 | 162 | ## Protocol Conformance Isolation Mismatch 163 | 164 | A protocol defines requirements that a conforming type must satisfy, 165 | including static isolation. 166 | This can result in isolation mismatches between a protocol's declaration and 167 | conforming types. 168 | 169 | There are many possible solutions to this class of problem, but they often 170 | involve trade-offs. 171 | Choosing an appropriate approach first requires understanding _why_ there is a 172 | mismatch in the first place. 173 | 174 | > Experiment: These code examples are available in package form. 175 | Try them out yourself in [ConformanceMismatches.swift][ConformanceMismatches]. 176 | 177 | [ConformanceMismatches]: https://github.com/apple/swift-migration-guide/blob/main/Sources/Examples/ConformanceMismatches.swift 178 | 179 | ### Under-Specified Protocol 180 | 181 | The most commonly-encountered form of this problem happens when a protocol 182 | has no explicit isolation. 183 | In this case, as with all other declarations, this implies _non-isolated_. 184 | Non-isolated protocol requirements can be called from generic code in any 185 | isolation domain. If the requirement is synchronous, it is invalid for 186 | a conforming type's implementation to access actor-isolated state: 187 | 188 | ```swift 189 | protocol Styler { 190 | func applyStyle() 191 | } 192 | 193 | @MainActor 194 | class WindowStyler: Styler { 195 | func applyStyle() { 196 | // access main-actor-isolated state 197 | } 198 | } 199 | ``` 200 | 201 | The above code produces the following error in Swift 6 mode: 202 | 203 | ``` 204 | 5 | @MainActor 205 | 6 | class WindowStyler: Styler { 206 | 7 | func applyStyle() { 207 | | |- error: main actor-isolated instance method 'applyStyle()' cannot be used to satisfy nonisolated protocol requirement 208 | | `- note: add 'nonisolated' to 'applyStyle()' to make this instance method not isolated to the actor 209 | 8 | // access main-actor-isolated state 210 | 9 | } 211 | ``` 212 | 213 | It is possible that the protocol actually _should_ be isolated, but 214 | has not yet been updated for concurrency. 215 | If conforming types are migrated to add correct isolation first, mismatches 216 | will occur. 217 | 218 | ```swift 219 | // This really only makes sense to use from MainActor types, but 220 | // has not yet been updated to reflect that. 221 | protocol Styler { 222 | func applyStyle() 223 | } 224 | 225 | // A conforming type, which is now correctly isolated, has exposed 226 | // a mismatch. 227 | @MainActor 228 | class WindowStyler: Styler { 229 | } 230 | ``` 231 | 232 | #### Adding Isolation 233 | 234 | If protocol requirements are always called from the main actor, 235 | adding `@MainActor` is the best solution. 236 | 237 | There are two ways to isolate a protocol requirement to the main actor: 238 | 239 | ```swift 240 | // entire protocol 241 | @MainActor 242 | protocol Styler { 243 | func applyStyle() 244 | } 245 | 246 | // per-requirement 247 | protocol Styler { 248 | @MainActor 249 | func applyStyle() 250 | } 251 | ``` 252 | 253 | Marking a protocol with a global actor attribute will infer isolation 254 | for the entire scope of the conformance. 255 | This can apply to a conforming type as a whole if the protocol conformance is 256 | not declared in an extension. 257 | 258 | Per-requirement isolation has a narrower impact on actor isolation inference, 259 | because it only applies to the implementation of that specific requirement. 260 | It does not impact the inferred isolation of protocol extensions or other 261 | methods on the conforming type. 262 | This approach should be favored if it makes sense to have conforming types 263 | that aren't necessarily also tied to the same global actor. 264 | 265 | Either way, changing the isolation of a protocol can affect the isolation of 266 | conforming types and it can impose restrictions on generic code using the 267 | protocol. 268 | 269 | You can stage in diagnostics caused by adding global actor isolation on a 270 | protocol using [`@preconcurrency`][Preconcurrency]. 271 | This will preserve source compatibility with clients that have not yet 272 | begun adopting concurrency. 273 | 274 | [Preconcurrency]: 275 | 276 | ```swift 277 | @preconcurrency @MainActor 278 | protocol Styler { 279 | func applyStyle() 280 | } 281 | ``` 282 | 283 | #### Asynchronous Requirements 284 | 285 | For methods that implement synchronous protocol requirements the isolation 286 | of implementations must match exactly. 287 | Making a requirement _asynchronous_ offers more flexibility for 288 | conforming types. 289 | 290 | ```swift 291 | protocol Styler { 292 | func applyStyle() async 293 | } 294 | ``` 295 | 296 | It's possible to satisfy a non-isolated `async` protocol requirement with 297 | an isolated method. 298 | 299 | ```swift 300 | @MainActor 301 | class WindowStyler: Styler { 302 | // matches, even though it is synchronous and actor-isolated 303 | func applyStyle() { 304 | } 305 | } 306 | ``` 307 | 308 | The above code is safe, because generic code must always call `applyStyle()` 309 | asynchronously, allowing isolated implementations to switch actors before 310 | accessing actor-isolated state. 311 | 312 | However, this flexibility comes at a cost. 313 | Changing a method to be asynchronous can have a significant impact at 314 | every call site. 315 | In addition to an async context, both the parameters and return values may 316 | need to cross isolation boundaries. 317 | Together, these could require significant structural changes to address. 318 | This may still be the right solution, but the side-effects should be carefully 319 | considered first, even if only a small number of types are involved. 320 | 321 | #### Preconcurrency Conformance 322 | 323 | Swift has a number of mechanisms to help you adopt concurrency incrementally 324 | and interoperate with code that has not yet begun using concurrency at all. 325 | These tools can be helpful both for code you do not own, as well as code you 326 | do own, but cannot easily change. 327 | 328 | Annotating a protocol conformance with `@preconcurrency` makes it possible to 329 | suppress errors about any isolation mismatches. 330 | 331 | ```swift 332 | @MainActor 333 | class WindowStyler: @preconcurrency Styler { 334 | func applyStyle() { 335 | // implementation body 336 | } 337 | } 338 | ``` 339 | 340 | This inserts runtime checks to ensure that that static isolation 341 | of the conforming class is always enforced. 342 | 343 | > Note: To learn more about incremental adoption and dynamic isolation, 344 | see [Dynamic Isolation][] 345 | 346 | [Dynamic Isolation]: 347 | 348 | ### Isolated Conforming Type 349 | 350 | So far, the solutions presented assume that the causes of isolation 351 | mismatches are ultimately rooted in protocol definitions. 352 | But it could be that the protocol's static isolation is appropriate, 353 | and the issue instead is only caused by the conforming type. 354 | 355 | #### Non-Isolated 356 | 357 | Even a completely non-isolated function could still be useful. 358 | 359 | ```swift 360 | @MainActor 361 | class WindowStyler: Styler { 362 | nonisolated func applyStyle() { 363 | // perhaps this implementation doesn't involve 364 | // other MainActor-isolated state 365 | } 366 | } 367 | ``` 368 | 369 | The constraint on this implementation is isolated state and functions 370 | become unavailable. 371 | This can still be an appropriate solution, especially if the function is used 372 | as a source of instance-independent configuration. 373 | 374 | #### Conformance by Proxy 375 | 376 | It's possible to use an intermediate type to help address static 377 | isolation differences. 378 | This can be particularly effective if the protocol requires inheritance by its 379 | conforming types. 380 | 381 | ```swift 382 | class UIStyler { 383 | } 384 | 385 | protocol Styler: UIStyler { 386 | func applyStyle() 387 | } 388 | 389 | // actors cannot have class-based inheritance 390 | actor WindowStyler: Styler { 391 | } 392 | ``` 393 | 394 | Introducing a new type to conform indirectly can make this situation work. 395 | However, this solution will require some structural changes to `WindowStyler` 396 | that could spill out to dependent code as well. 397 | 398 | ```swift 399 | // class with necessary superclass 400 | class CustomWindowStyle: UIStyler { 401 | } 402 | 403 | // now, the conformance is possible 404 | extension CustomWindowStyle: Styler { 405 | func applyStyle() { 406 | } 407 | } 408 | ``` 409 | 410 | Here, a new type has been created that can satisfy the needed inheritance. 411 | Incorporating will be easiest if the conformance is only used internally by 412 | `WindowStyler`. 413 | 414 | ## Crossing Isolation Boundaries 415 | 416 | The compiler will only permit a value to move from one isolation domain to 417 | another when it can prove it will not introduce data races. 418 | Attempting to use values that do not satisfy this requirement in contexts that 419 | can cross isolation boundaries is a very common problem. 420 | And because libraries and frameworks may be updated to use Swift's 421 | concurrency features, these issues can come up even when your code hasn't 422 | changed. 423 | 424 | > Experiment: These code examples are available in package form. 425 | Try them out yourself in [Boundaries.swift][Boundaries]. 426 | 427 | [Boundaries]: https://github.com/apple/swift-migration-guide/blob/main/Sources/Examples/Boundaries.swift 428 | 429 | ### Implicitly-Sendable Types 430 | 431 | Many value types consist entirely of `Sendable` properties. 432 | The compiler will treat types like this as implicitly `Sendable`, but _only_ 433 | when they are non-public. 434 | 435 | ```swift 436 | public struct ColorComponents { 437 | public let red: Float 438 | public let green: Float 439 | public let blue: Float 440 | } 441 | 442 | @MainActor 443 | func applyBackground(_ color: ColorComponents) { 444 | } 445 | 446 | func updateStyle(backgroundColor: ColorComponents) async { 447 | await applyBackground(backgroundColor) 448 | } 449 | ``` 450 | 451 | A `Sendable` conformance is part of a type's public API contract, 452 | which is up to you to declare. 453 | Because `ColorComponents` is marked `public`, it will not implicitly 454 | conform to `Sendable`. 455 | This will result in the following error: 456 | 457 | ``` 458 | 6 | 459 | 7 | func updateStyle(backgroundColor: ColorComponents) async { 460 | 8 | await applyBackground(backgroundColor) 461 | | |- error: sending 'backgroundColor' risks causing data races 462 | | `- note: sending task-isolated 'backgroundColor' to main actor-isolated global function 'applyBackground' risks causing data races between main actor-isolated and task-isolated uses 463 | 9 | } 464 | 10 | 465 | ``` 466 | 467 | A straightforward solution is to make the type's `Sendable` 468 | conformance explicit: 469 | 470 | ```swift 471 | public struct ColorComponents: Sendable { 472 | // ... 473 | } 474 | ``` 475 | 476 | Even when trivial, adding `Sendable` conformance should always be 477 | done with care. 478 | Remember that `Sendable` is a guarantee of thread-safety and 479 | removing the conformance is an API-breaking change. 480 | 481 | ### Preconcurrency Import 482 | 483 | Even if the type in another module is actually `Sendable`, it is not always 484 | possible to modify its definition. 485 | In this case, you can use a `@preconcurrency import` to downgrade diagnostics 486 | until the library is updated. 487 | 488 | ```swift 489 | // ColorComponents defined here 490 | @preconcurrency import UnmigratedModule 491 | 492 | func updateStyle(backgroundColor: ColorComponents) async { 493 | // crossing an isolation domain here 494 | await applyBackground(backgroundColor) 495 | } 496 | ``` 497 | 498 | With the addition of this `@preconcurrency import`, 499 | `ColorComponents` remains non-`Sendable`. 500 | However, the compiler's behavior will be altered. 501 | When using the Swift 6 language mode, 502 | the error produced here will be downgraded to a warning. 503 | The Swift 5 language mode will produce no diagnostics at all. 504 | 505 | ### Latent Isolation 506 | 507 | Sometimes the _apparent_ need for a `Sendable` type can actually be the 508 | symptom of a more fundamental isolation problem. 509 | The only reason a type needs to be `Sendable` is to cross isolation boundaries. 510 | If you can avoid crossing boundaries altogether, the result can 511 | often be both simpler and a better reflection of the true nature of your 512 | system. 513 | 514 | ```swift 515 | @MainActor 516 | func applyBackground(_ color: ColorComponents) { 517 | } 518 | 519 | func updateStyle(backgroundColor: ColorComponents) async { 520 | await applyBackground(backgroundColor) 521 | } 522 | ``` 523 | 524 | The `updateStyle(backgroundColor:)` function is non-isolated. 525 | This means that its non-`Sendable` parameter is also non-isolated. 526 | The implementation crosses immediately from this non-isolated domain to the 527 | `MainActor` when `applyBackground(_:)` is called. 528 | 529 | Since `updateStyle(backgroundColor:)` is working directly with 530 | `MainActor`-isolated functions and non-`Sendable` types, 531 | just applying `MainActor` isolation may be more appropriate. 532 | 533 | ```swift 534 | @MainActor 535 | func updateStyle(backgroundColor: ColorComponents) async { 536 | applyBackground(backgroundColor) 537 | } 538 | ``` 539 | 540 | Now, there is no longer an isolation boundary for the non-`Sendable` type to 541 | cross. 542 | And in this case, not only does this resolve the problem, it also 543 | removes the need for an asynchronous call. 544 | Fixing latent isolation issues can also potentially make further API 545 | simplification possible. 546 | 547 | Lack of `MainActor` isolation like this is, by far, the most common form of 548 | latent isolation. 549 | It is also very common for developers to hesitate to use this as a solution. 550 | It is completely normal for programs with a user interface to have a large 551 | set of `MainActor`-isolated state. 552 | Concerns around long-running _synchronous_ work can often be addressed with 553 | just a handful of targeted `nonisolated` functions. 554 | 555 | ### Computed Value 556 | 557 | Instead of trying to pass a non-`Sendable` type across a boundary, it may be 558 | possible to use a `Sendable` function that creates the needed values. 559 | 560 | ```swift 561 | func updateStyle(backgroundColorProvider: @Sendable () -> ColorComponents) async { 562 | await applyBackground(using: backgroundColorProvider) 563 | } 564 | ``` 565 | 566 | Here, it does not matter than `ColorComponents` is not `Sendable`. 567 | By using `@Sendable` function that can compute the value, the lack of 568 | sendability is side-stepped entirely. 569 | 570 | ### Sending Argument 571 | 572 | The compiler will permit non-`Sendable` values to cross an isolation boundary 573 | if the compiler can prove it can be done safely. 574 | Functions that explicitly state they require this can use the values 575 | within their implementations with less restrictions. 576 | 577 | ```swift 578 | func updateStyle(backgroundColor: sending ColorComponents) async { 579 | // this boundary crossing can now be proven safe in all cases 580 | await applyBackground(backgroundColor) 581 | } 582 | ``` 583 | 584 | A `sending` argument does impose some restrictions at call sites. 585 | But, this can still be easier or more appropriate than adding a 586 | `Sendable` conformance. 587 | This technique also works for types you do not control. 588 | 589 | ### Sendable Conformance 590 | 591 | When encountering problems related to crossing isolation domains, a very 592 | natural reaction is to just try to add a conformance to `Sendable`. 593 | You can make a type `Sendable` in four ways. 594 | 595 | #### Global Isolation 596 | 597 | Adding global isolation to any type will make it implicitly `Sendable`. 598 | 599 | ```swift 600 | @MainActor 601 | public struct ColorComponents { 602 | // ... 603 | } 604 | ``` 605 | 606 | By isolating this type to the `MainActor`, any accesses from other isolation domains 607 | must be done asynchronously. 608 | This makes it possible to safely pass instances around across domains. 609 | 610 | #### Actors 611 | 612 | Actors have an implicit `Sendable` conformance because their properties are 613 | protected by actor isolation. 614 | 615 | ```swift 616 | actor Style { 617 | private var background: ColorComponents 618 | } 619 | ``` 620 | 621 | In addition to gaining a `Sendable` conformance, actors receive their own 622 | isolation domain. 623 | This allows them to work freely with other non-`Sendable` types internally. 624 | This can be a major advantage, but does come with trade-offs. 625 | 626 | Because an actor's isolated methods must all be asynchronous, 627 | sites that access the type may require an async context. 628 | This alone is a reason to make such a change with care. 629 | But further, data that is passed into or out of the actor may itself 630 | need to cross the isolation boundary. 631 | This can result in the need for yet more `Sendable` types. 632 | 633 | ```swift 634 | actor Style { 635 | private var background: ColorComponents 636 | 637 | func applyBackground(_ color: ColorComponents) { 638 | // make use of non-Sendable data here 639 | } 640 | } 641 | ``` 642 | 643 | By moving both the non-Sendable data *and* operations on that data into the 644 | actor, no isolation boundaries need to be crossed. 645 | This provides a `Sendable` interface to those operations that can be freely 646 | accessed from any asynchronous context. 647 | 648 | #### Manual Synchronization 649 | 650 | If you have a type that is already doing manual synchronization, you can 651 | express this to the compiler by marking your `Sendable` conformance as 652 | `unchecked`. 653 | 654 | ```swift 655 | class Style: @unchecked Sendable { 656 | private var background: ColorComponents 657 | private let queue: DispatchQueue 658 | } 659 | ``` 660 | 661 | You should not feel compelled to remove the use of queues, locks, or other 662 | forms of manual synchronization to integrate with Swift's concurrency system. 663 | However, most types are not inherently thread-safe. 664 | As a general rule, if a type isn't already thread-safe, attempting to make 665 | it `Sendable` should not be your first approach. 666 | It is often easier to try other techniques first, falling back to 667 | manual synchronization only when truly necessary. 668 | 669 | #### Retroactive Sendable Conformance 670 | 671 | Your dependencies may also expose types that are using manual synchronization. 672 | This is usually visible only via documentation. 673 | It is possible to add an `@unchecked Sendable` conformance in this case as well. 674 | 675 | ```swift 676 | extension ColorComponents: @retroactive @unchecked Sendable { 677 | } 678 | ``` 679 | 680 | Because `Sendable` is a marker protocol, a retroactive conformance 681 | does not have direct binary compatibility issues. 682 | However, it should still be used with extreme caution. 683 | Types that use manual synchronization can come with conditions or 684 | exceptions to their safety that may not completely match the semantics of 685 | `Sendable`. 686 | Further, you should be _particularly_ careful about using this technique 687 | for types that are part of your system's public API. 688 | 689 | > Note: To learn more about retroactive conformances, 690 | see the associated [Swift evolution proposal][SE-0364]. 691 | 692 | [SE-0364]: https://github.com/swiftlang/swift-evolution/blob/main/proposals/0364-retroactive-conformance-warning.md 693 | 694 | #### Sendable Reference Types 695 | 696 | It is possible for reference types to be validated as `Sendable` without 697 | the `unchecked` qualifier, 698 | but this is only done under very specific circumstances. 699 | 700 | To allow a checked `Sendable` conformance, a class: 701 | 702 | - Must be `final` 703 | - Cannot inherit from another class other than `NSObject` 704 | - Cannot have any non-isolated mutable properties 705 | 706 | ```swift 707 | public struct ColorComponents: Sendable { 708 | // ... 709 | } 710 | 711 | final class Style: Sendable { 712 | private let background: ColorComponents 713 | } 714 | ``` 715 | 716 | A reference type that conforms to `Sendable` is sometimes a sign that a value 717 | type would be preferable. 718 | But there are circumstances where reference semantics need to be preserved, 719 | or where compatibility with a mixed Swift/Objective-C code base is required. 720 | 721 | #### Using Composition 722 | 723 | You do not need to select one single technique for making a reference type 724 | `Sendable.` 725 | One type can use many techniques internally. 726 | 727 | ```swift 728 | final class Style: Sendable { 729 | private nonisolated(unsafe) var background: ColorComponents 730 | private let queue: DispatchQueue 731 | 732 | @MainActor 733 | private var foreground: ColorComponents 734 | } 735 | ``` 736 | 737 | The `background` property is protected by manual synchronization, 738 | while the `foreground` property uses actor isolation. 739 | Combining these two techniques results in a type that better describes its 740 | internal semantics. 741 | By doing this, the type continues to take advantage of the 742 | compiler's automated isolation checking. 743 | 744 | ### Non-Isolated Initialization 745 | 746 | Actor-isolated types can present a problem when they are initialized in 747 | a non-isolated context. 748 | This frequently occurs when the type is used in a default value expression or 749 | as a property initializer. 750 | 751 | > Note: These problems could also be a symptom of 752 | [latent isolation](#Latent-Isolation) or an 753 | [under-specified protocol](#Under-Specified-Protocol). 754 | 755 | Here the non-isolated `Stylers` type is making a call to a 756 | `MainActor`-isolated initializer. 757 | 758 | ```swift 759 | @MainActor 760 | class WindowStyler { 761 | init() { 762 | } 763 | } 764 | 765 | struct Stylers { 766 | static let window = WindowStyler() 767 | } 768 | ``` 769 | 770 | This code results in the following error: 771 | 772 | ``` 773 | 7 | 774 | 8 | struct Stylers { 775 | 9 | static let window = WindowStyler() 776 | | `- error: main actor-isolated default value in a nonisolated context 777 | 10 | } 778 | 11 | 779 | ``` 780 | 781 | Globally-isolated types sometimes don't actually need to reference any global 782 | actor state in their initializers. 783 | By making the `init` method `nonisolated`, it is free to be called from any 784 | isolation domain. 785 | This remains safe as the compiler still guarantees that any state that *is* 786 | isolated will only be accessible from the `MainActor`. 787 | 788 | ```swift 789 | @MainActor 790 | class WindowStyler { 791 | private var viewStyler = ViewStyler() 792 | private var primaryStyleName: String 793 | 794 | nonisolated init(name: String) { 795 | self.primaryStyleName = name 796 | // type is fully-initialized here 797 | } 798 | } 799 | ``` 800 | 801 | 802 | All `Sendable` properties can still be safely accessed in this `init` method. 803 | And while any non-`Sendable` properties cannot, 804 | they can still be initialized by using default expressions. 805 | 806 | ### Non-Isolated Deinitialization 807 | 808 | Even if a type has actor isolation, deinitializers are _always_ non-isolated. 809 | 810 | ```swift 811 | actor BackgroundStyler { 812 | // another actor-isolated type 813 | private let store = StyleStore() 814 | 815 | deinit { 816 | // this is non-isolated 817 | store.stopNotifications() 818 | } 819 | } 820 | ``` 821 | 822 | This code produces the error: 823 | 824 | ``` 825 | error: call to actor-isolated instance method 'stopNotifications()' in a synchronous nonisolated context 826 | 5 | deinit { 827 | 6 | // this is non-isolated 828 | 7 | store.stopNotifications() 829 | | `- error: call to actor-isolated instance method 'stopNotifications()' in a synchronous nonisolated context 830 | 8 | } 831 | 9 | } 832 | ``` 833 | 834 | While this might feel surprising, given that this type is an actor, 835 | this is not a new constraint. 836 | The thread that executes a deinitializer has never been guaranteed and 837 | Swift's data isolation is now just surfacing that fact. 838 | 839 | Often, the work being done within the `deinit` does not need to be synchronous. 840 | A solution is to use an unstructured `Task` to first capture and 841 | then operate on the isolated values. 842 | When using this technique, 843 | it is _critical_ to ensure you do not capture `self`, even implicitly. 844 | 845 | ```swift 846 | actor BackgroundStyler { 847 | // another actor-isolated type 848 | private let store = StyleStore() 849 | 850 | deinit { 851 | // no actor isolation here, so none will be inherited by the task 852 | Task { [store] in 853 | await store.stopNotifications() 854 | } 855 | } 856 | } 857 | ``` 858 | 859 | > Important: **Never** extend the life-time of `self` from within 860 | `deinit`. Doing so will crash at runtime. 861 | -------------------------------------------------------------------------------- /Guide.docc/CompleteChecking.md: -------------------------------------------------------------------------------- 1 | # Enabling Complete Concurrency Checking 2 | 3 | Incrementally address data-race safety issues by enabling diagnostics as warnings in your project. 4 | 5 | Data-race safety in the Swift 6 language mode is designed for incremental 6 | migration. You can address data-race safety issues in your projects 7 | module-by-module, and you can enable the compiler's actor isolation and 8 | `Sendable` checking as warnings in the Swift 5 language mode, allowing you to 9 | assess your progress toward eliminating data races before turning on the 10 | Swift 6 language mode. 11 | 12 | Complete data-race safety checking can be enabled as warnings in the Swift 5 13 | language mode using the `-strict-concurrency` compiler flag. 14 | 15 | ## Using the Swift compiler 16 | 17 | To enable complete concurrency checking when running `swift` or `swiftc` 18 | directly at the command line, pass `-strict-concurrency=complete`: 19 | 20 | ``` 21 | ~ swift -strict-concurrency=complete main.swift 22 | ``` 23 | 24 | ## Using SwiftPM 25 | 26 | ### Command-line invocation 27 | 28 | `-strict-concurrency=complete` can be passed in a Swift package manager 29 | command-line invocation using the `-Xswiftc` flag: 30 | 31 | ``` 32 | ~ swift build -Xswiftc -strict-concurrency=complete 33 | ~ swift test -Xswiftc -strict-concurrency=complete 34 | ``` 35 | 36 | This can be useful to gauge the amount of concurrency warnings before adding 37 | the flag permanently in the package manifest as described in the following 38 | section. 39 | 40 | ### Package manifest 41 | 42 | To enable complete concurrency checking for a target in a Swift package using 43 | Swift 5.9 or Swift 5.10 tools, use [`SwiftSetting.enableExperimentalFeature`](https://developer.apple.com/documentation/packagedescription/swiftsetting/enableexperimentalfeature(_:_:)) 44 | in the Swift settings for the given target: 45 | 46 | ```swift 47 | .target( 48 | name: "MyTarget", 49 | swiftSettings: [ 50 | .enableExperimentalFeature("StrictConcurrency") 51 | ] 52 | ) 53 | ``` 54 | 55 | When using Swift 6.0 tools or later, use [`SwiftSetting.enableUpcomingFeature`](https://developer.apple.com/documentation/packagedescription/swiftsetting/enableupcomingfeature(_:_:)) 56 | in the Swift settings for a pre-Swift 6 language mode target: 57 | 58 | ```swift 59 | .target( 60 | name: "MyTarget", 61 | swiftSettings: [ 62 | .enableUpcomingFeature("StrictConcurrency") 63 | ] 64 | ) 65 | ``` 66 | 67 | Targets that adopt the Swift 6 language mode have complete checking 68 | enabled unconditionally and do not require any settings changes. 69 | 70 | ## Using Xcode 71 | 72 | ### Build Settings 73 | 74 | To enable complete concurrency checking in an Xcode project, set the 75 | "Strict Concurrency Checking" setting to "Complete" in the Xcode build 76 | settings. 77 | 78 | ### XCConfig 79 | 80 | Alternatively, you can set `SWIFT_STRICT_CONCURRENCY` to `complete` 81 | in an xcconfig file: 82 | 83 | ``` 84 | // In a Settings.xcconfig 85 | 86 | SWIFT_STRICT_CONCURRENCY = complete; 87 | ``` 88 | -------------------------------------------------------------------------------- /Guide.docc/DataRaceSafety.md: -------------------------------------------------------------------------------- 1 | # Data Race Safety 2 | 3 | Learn about the fundamental concepts Swift uses to enable data-race-free 4 | concurrent code. 5 | 6 | Traditionally, mutable state had to be manually protected via careful runtime 7 | synchronization. 8 | Using tools such as locks and queues, the prevention of data races was 9 | entirely up to the programmer. This is notoriously difficult 10 | not just to do correctly, but also to keep correct over time. 11 | Even determining the _need_ for synchronization may be challenging. 12 | Worst of all, unsafe code does not guarantee failure at runtime. 13 | This code can often seem to work, possibly because highly unusual conditions 14 | are required to exhibit the incorrect and unpredictable behavior characteristic 15 | of a data race. 16 | 17 | More formally, a data race occurs when one thread accesses memory while the 18 | same memory is being mutated by another thread. 19 | The Swift 6 language mode eliminates these problems by preventing data races 20 | at compile time. 21 | 22 | > Important: You may have encountered constructs like `async`/`await` 23 | and actors in other languages. Pay extra attention, as similarities to 24 | these concepts in Swift may only be superficial. 25 | 26 | ## Data Isolation 27 | 28 | Swift's concurrency system allows the compiler to understand and verify the 29 | safety of all mutable state. 30 | It does this with a mechanism called _data isolation_. 31 | Data isolation guarantees mutually exclusive 32 | access to mutable state. It is a form of synchronization, 33 | conceptually similar to a lock. 34 | But unlike a lock, the protection data isolation provides happens at 35 | compile-time. 36 | 37 | A Swift programmer interacts with data isolation in two ways: 38 | statically and dynamically. 39 | 40 | The term _static_ is used to describe program elements that are unaffected by 41 | runtime state. These elements, such as a function definition, 42 | are made up of keywords and annotations. Swift's concurrency system is 43 | an extension of its type system. When you declare functions and types, 44 | you are doing so statically. Isolation can be a part of these static 45 | declarations. 46 | 47 | There are cases, however, where the type system alone cannot sufficiently 48 | describe runtime behavior. An example could be an Objective-C type 49 | that has been exposed to Swift. This declaration, made outside of Swift code, 50 | may not provide enough information to the compiler to ensure safe usage. To 51 | accommodate these situations, there are additional features that allow you 52 | to express isolation requirements dynamically. 53 | 54 | Data isolation, be it static or dynamic, allows the 55 | compiler to guarantee Swift code you write is free of data races. 56 | 57 | > Note: For more information about using dynamic isolation, 58 | see 59 | 60 | ### Isolation Domains 61 | 62 | Data isolation is the _mechanism_ used to protect shared mutable state. 63 | But it is often useful to talk about an independent unit of isolation. 64 | This is known as an _isolation domain_. 65 | How much state a particular domain is responsible for 66 | protecting varies widely. An isolation domain might protect a single variable, 67 | or an entire subsystem, such as a user interface. 68 | 69 | The critical feature of an isolation domain is the safety it provides. 70 | Mutable state can only be accessed from one isolation domain at a time. 71 | You can pass mutable state from one isolation domain to another, but you can 72 | never access that state concurrently from a different domain. 73 | This guarantee is validated by the compiler. 74 | 75 | Even if you have not explicitly defined it yourself, 76 | _all_ function and variable declarations have a well-defined static 77 | isolation domain. 78 | These domains will always fall into one of three categories: 79 | 80 | 1. Non-isolated 81 | 2. Isolated to an actor value 82 | 3. Isolated to a global actor 83 | 84 | ### Non-isolated 85 | 86 | Functions and variables do not have to be a part of an explicit isolation 87 | domain. 88 | In fact, a lack of isolation is the default, called _non-isolated_. 89 | Because all the data isolation rules apply, 90 | there is no way for non-isolated code to mutate state protected in another 91 | domain. 92 | 93 | 102 | 103 | ```swift 104 | func sailTheSea() { 105 | } 106 | ``` 107 | 108 | This top-level function has no static isolation, making it non-isolated. 109 | It can safely call other non-isolated functions, and access non-isolated 110 | variables, but it cannot access anything from another isolation domain. 111 | 112 | ```swift 113 | class Chicken { 114 | let name: String 115 | var currentHunger: HungerLevel 116 | } 117 | ``` 118 | 119 | This is an example of a non-isolated type. 120 | Inheritance can play a role in static isolation. 121 | But this simple class, with no superclass or protocol conformances, 122 | also uses the default isolation. 123 | 124 | Data isolation guarantees that non-isolated entities cannot access the mutable 125 | state of other domains. 126 | As a result of this, non-isolated functions and variables are always safe to 127 | access from any other domain. 128 | 129 | ### Actors 130 | 131 | Actors give the programmer a way to define an isolation domain, 132 | along with methods that operate within that domain. 133 | All stored properties of an actor are isolated to the enclosing actor instance. 134 | 135 | ```swift 136 | actor Island { 137 | var flock: [Chicken] 138 | var food: [Pineapple] 139 | 140 | func addToFlock() { 141 | flock.append(Chicken()) 142 | } 143 | } 144 | ``` 145 | 146 | Here, every `Island` instance will define a new domain, 147 | which will be used to protect access to its properties. 148 | The method `Island.addToFlock` is said to be isolated to `self`. 149 | The body of a method has access to all data that shares its isolation domain, 150 | making the `flock` property synchronously accessible. 151 | 152 | Actor isolation can be selectively disabled. 153 | This can be useful any time you want to keep code organized within an 154 | isolated type, but opt-out of the isolation requirements that go along with it. 155 | Non-isolated methods cannot synchronously access any protected state. 156 | 157 | ```swift 158 | actor Island { 159 | var flock: [Chicken] 160 | var food: [Pineapple] 161 | 162 | nonisolated func canGrow() -> PlantSpecies { 163 | // neither flock nor food are accessible here 164 | } 165 | } 166 | ``` 167 | 168 | The isolation domain of an actor is not limited to its own methods. 169 | Functions that accept an isolated parameter can also gain access to 170 | actor-isolated state without the need for any other form of synchronization. 171 | 172 | ```swift 173 | func addToFlock(of island: isolated Island) { 174 | island.flock.append(Chicken()) 175 | } 176 | ``` 177 | 178 | > Note: For an overview of actors, please see the [Actors][] section of 179 | The Swift Programming Language. 180 | 181 | [Actors]: https://docs.swift.org/swift-book/documentation/the-swift-programming-language/concurrency#Actors 182 | 183 | ### Global Actors 184 | 185 | Global actors share all of the properties of regular actors, but also provide 186 | a means of statically assigning declarations to their isolation domain. 187 | This is done with an annotation matching the actor name. 188 | Global actors are particularly useful when groups of types all need to 189 | interoperate as a single pool of shared mutable state. 190 | 191 | ```swift 192 | @MainActor 193 | class ChickenValley { 194 | var flock: [Chicken] 195 | var food: [Pineapple] 196 | } 197 | ``` 198 | 199 | This class is statically-isolated to `MainActor`. This ensures that all access 200 | to its mutable state is done from that isolation domain. 201 | 202 | You can opt-out of this type of actor isolation as well, 203 | using the `nonisolated` keyword. 204 | And just as with actor types, 205 | doing so will disallow access to any protected state. 206 | 207 | ```swift 208 | @MainActor 209 | class ChickenValley { 210 | var flock: [Chicken] 211 | var food: [Pineapple] 212 | 213 | nonisolated func canGrow() -> PlantSpecies { 214 | // neither flock, food, nor any other MainActor-isolated 215 | // state is accessible here 216 | } 217 | } 218 | ``` 219 | 220 | ### Tasks 221 | 222 | A `task` is a unit of work that can run concurrently within your program. 223 | You cannot run concurrent code in Swift outside of a task, 224 | but that doesn't mean you must always manually start one. 225 | Typically, asynchronous functions do not need to be aware of the 226 | task running them. 227 | In fact, tasks can often begin at a much higher level, 228 | within an application framework, or even at the entry point of the program. 229 | 230 | Tasks may run concurrently with one another, 231 | but each individual task only executes one function at a time. 232 | They run code in order, from beginning to end. 233 | 234 | ```swift 235 | Task { 236 | flock.map(Chicken.produce) 237 | } 238 | ``` 239 | 240 | A task always has an isolation domain. They can be isolated to an 241 | actor instance, a global actor, or could be non-isolated. 242 | This isolation can be established manually, but can also be inherited 243 | automatically based on context. 244 | Task isolation, just like all other Swift code, determines what mutable state 245 | is accessible. 246 | 247 | Tasks can run both synchronous and asynchronous code. Regardless of the 248 | structure and how many tasks are involved, functions in the same isolation 249 | domain cannot run concurrently with each other. 250 | There will only ever be one task running synchronous code for any given 251 | isolation domain. 252 | 253 | > Note: For more information see the [Tasks][] section of 254 | The Swift Programming Language. 255 | 256 | [Tasks]: https://docs.swift.org/swift-book/documentation/the-swift-programming-language/concurrency#Tasks-and-Task-Groups 257 | 258 | ### Isolation Inference and Inheritance 259 | 260 | There are many ways to specify isolation explicitly. 261 | But there are cases where the context of a declaration establishes isolation 262 | implicitly, via _isolation inference_. 263 | 264 | #### Classes 265 | 266 | A subclass will always have the same isolation as its parent. 267 | 268 | ```swift 269 | @MainActor 270 | class Animal { 271 | } 272 | 273 | class Chicken: Animal { 274 | } 275 | ``` 276 | 277 | Because `Chicken` inherits from `Animal`, the static isolation of the `Animal` 278 | type also implicitly applies. 279 | Not only that, it also cannot be changed by a subclass. 280 | All `Animal` instances have been declared to be `MainActor`-isolated, which 281 | means all `Chicken` instances must be as well. 282 | 283 | The static isolation of a type will also be inferred for its properties and 284 | methods by default. 285 | 286 | ```swift 287 | @MainActor 288 | class Animal { 289 | // all declarations within this type are also 290 | // implicitly MainActor-isolated 291 | let name: String 292 | 293 | func eat(food: Pineapple) { 294 | } 295 | } 296 | ``` 297 | 298 | > Note: For more information, see the [Inheritance][] section of 299 | The Swift Programming Language. 300 | 301 | [Inheritance]: https://docs.swift.org/swift-book/documentation/the-swift-programming-language/inheritance 302 | 303 | #### Protocols 304 | 305 | A protocol conformance can implicitly affect isolation. 306 | However, the protocol's effect on isolation depends on how the conformance 307 | is applied. 308 | 309 | ```swift 310 | @MainActor 311 | protocol Feedable { 312 | func eat(food: Pineapple) 313 | } 314 | 315 | // inferred isolation applies to the entire type 316 | class Chicken: Feedable { 317 | } 318 | 319 | // inferred isolation only applies within the extension 320 | extension Pirate: Feedable { 321 | } 322 | ``` 323 | 324 | A protocol's requirements themselves can also be isolated. 325 | This allows more fine-grained control around how isolation is inferred 326 | for conforming types. 327 | 328 | ```swift 329 | protocol Feedable { 330 | @MainActor 331 | func eat(food: Pineapple) 332 | } 333 | ``` 334 | 335 | Regardless of how a protocol is defined and conformance added, you cannot alter 336 | other mechanisms of static isolation. 337 | If a type is globally-isolated, either explicitly or via inference from a 338 | superclass, a protocol conformance cannot be used to change it. 339 | 340 | > Note: For more information, see the [Protocols][] section of 341 | The Swift Programming Language. 342 | 343 | [Protocols]: https://docs.swift.org/swift-book/documentation/the-swift-programming-language/protocols 344 | 345 | #### Function Types 346 | 347 | Isolation _inference_ allows a type to implicitly define the isolation of 348 | its properties and methods. 349 | But these are all examples of _declarations_. 350 | It is also possible to achieve a similar effect with function values, through 351 | isolation _inheritance_. 352 | 353 | By default, closures are isolated to the same context they're formed in. 354 | For example: 355 | 356 | ```swift 357 | @MainActor 358 | class Model { ... } 359 | 360 | @MainActor 361 | class C { 362 | var models: [Model] = [] 363 | 364 | func mapModels( 365 | _ keyPath: KeyPath 366 | ) -> some Collection { 367 | models.lazy.map { $0[keyPath: keyPath] } 368 | } 369 | } 370 | ``` 371 | 372 | In the above code, the closure to `LazySequence.map` has type 373 | `@escaping (Base.Element) -> U`. This closure must stay on the main 374 | actor where it was originally formed. This allows the closure to capture 375 | state or call isolated methods from the surrounding context. 376 | 377 | Closures that can run concurrently with the original context are marked 378 | explicitly through `@Sendable` and `sending` annotations described in later 379 | sections. 380 | 381 | For `async` closures that may be evaluated concurrently, the closure can still 382 | capture the isolation of the original context. This mechanism is used by the 383 | `Task` initializer so that the given operation is isolated to the original 384 | context by default, while still allowing explicit isolation to be specified: 385 | 386 | ```swift 387 | @MainActor 388 | func eat(food: Pineapple) { 389 | // the static isolation of this function's declaration is 390 | // captured by the closure created here 391 | Task { 392 | // allowing the closure's body to inherit MainActor-isolation 393 | Chicken.prizedHen.eat(food: food) 394 | } 395 | 396 | Task { @MyGlobalActor in 397 | // this task is isolated to `MyGlobalActor` 398 | } 399 | } 400 | ``` 401 | 402 | The closure's type here is defined by `Task.init`. 403 | Despite that declaration not being isolated to any actor, 404 | this newly-created task will _inherit_ the `MainActor` isolation of its 405 | enclosing scope unless an explicit global actor is written. 406 | Function types offer a number of mechanisms for controlling their 407 | isolation behavior, but by default they behave identically to other types. 408 | 409 | > Note: For more information, see the [Closures][] section of 410 | The Swift Programming Language. 411 | 412 | [Closures]: https://docs.swift.org/swift-book/documentation/the-swift-programming-language/closures 413 | 414 | ## Isolation Boundaries 415 | 416 | Isolation domains protect their mutable state, but useful programs need more 417 | than just protection. They have to communicate and coordinate, 418 | often by passing data back and forth. 419 | Moving values into or out of an isolation domain is known as _crossing_ an 420 | isolation boundary. 421 | Values are only ever permitted to cross an isolation boundary where there 422 | is no potential for concurrent access to shared mutable state. 423 | 424 | Values can cross boundaries directly, via asynchronous function calls. 425 | When you call an asynchronous function with a _different_ isolation domain, 426 | the parameters and return value need to move into that domain. 427 | Values can also cross boundaries indirectly when captured by closures. 428 | Closures introduce many potential opportunities for concurrent accesses. 429 | They can be created in one domain and then executed in another. 430 | They can even be executed in multiple, different domains. 431 | 432 | ### Sendable Types 433 | 434 | In some cases, all values of a particular type are safe to pass across 435 | isolation boundaries because thread-safety is a property of the type itself. 436 | This is represented by the `Sendable` protocol. 437 | A conformance to `Sendable` means the given type is thread safe, 438 | and values of the type can be shared across arbitrary isolation domains 439 | without introducing a risk of data races. 440 | 441 | Swift encourages using value types because they are naturally safe. 442 | With value types, different parts of your program can't have 443 | shared references to the same value. 444 | When you pass an instance of a value type to a function, 445 | the function has its own independent copy of that value. 446 | Because value semantics guarantees the absence of shared mutable state, value 447 | types in Swift are implicitly `Sendable` when all their stored properties 448 | are also Sendable. 449 | However, this implicit conformance is not visible outside of their 450 | defining module. 451 | Making a type `Sendable` is part of its public API contract 452 | and must always be done explicitly. 453 | 454 | ```swift 455 | enum Ripeness { 456 | case hard 457 | case perfect 458 | case mushy(daysPast: Int) 459 | } 460 | 461 | struct Pineapple { 462 | var weight: Double 463 | var ripeness: Ripeness 464 | } 465 | ``` 466 | 467 | Here, both the `Ripeness` and `Pineapple` types are implicitly `Sendable`, 468 | since they are composed entirely of `Sendable` value types. 469 | 470 | > Note: For more information see the [Sendable Types][] section of 471 | The Swift Programming Language. 472 | 473 | [Sendable Types]: https://docs.swift.org/swift-book/documentation/the-swift-programming-language/concurrency#Sendable-Types 474 | 475 | #### Flow-Sensitive Isolation Analysis 476 | 477 | The `Sendable` protocol is used to express thread-safety for a type as a 478 | whole. 479 | But there are situations when a particular _instance_ of a non-`Sendable` 480 | type is being used in a safe way. 481 | The compiler is often capable of inferring this safety through 482 | flow-sensitive analysis known as [region-based isolation][RBI]. 483 | 484 | Region-based isolation allows the compiler to permit instances of 485 | non-`Sendable` types to cross isolation domains when it can prove doing 486 | so cannot introduce data races. 487 | 488 | ```swift 489 | func populate(island: Island) async { 490 | let chicken = Chicken() 491 | 492 | await island.adopt(chicken) 493 | } 494 | ``` 495 | 496 | Here, the compiler can correctly reason that even though `chicken` has a 497 | non-`Sendable` type, allowing it to cross into the `island` isolation domain is 498 | safe. 499 | However, this exception to `Sendable` checking is inherently contigent on 500 | the surrounding code. 501 | The compiler will still produce an error should any unsafe accesses to the 502 | `chicken` variable ever be introduced. 503 | 504 | ```swift 505 | func populate(island: Island) async { 506 | let chicken = Chicken() 507 | 508 | await island.adopt(chicken) 509 | 510 | // this would result in an error 511 | chicken.eat(food: Pineapple()) 512 | } 513 | ``` 514 | 515 | [RBI]: https://github.com/swiftlang/swift-evolution/blob/main/proposals/0414-region-based-isolation.md 516 | 517 | Region-based isolation works without any code changes. 518 | But a function's parameters and return values can also explicitly state 519 | that they support crossing domains using this mechanism. 520 | 521 | ```swift 522 | func populate(island: Island, with chicken: sending Chicken) async { 523 | await island.adopt(chicken) 524 | } 525 | ``` 526 | 527 | The compiler can now provide the guarantee that at all call sites, the 528 | `chicken` parameter will never be subject to unsafe access. 529 | This is a relaxing of an otherwise significant constraint. 530 | Without `sending`, this function would only be possible to implement by 531 | requiring that `Chicken` first conform to `Sendable`. 532 | 533 | ### Actor-Isolated Types 534 | 535 | Actors are not value types, but because they protect all of their state 536 | in their own isolation domain, 537 | they are inherently safe to pass across boundaries. 538 | This makes all actor types implicitly `Sendable`, even if their properties 539 | are not `Sendable` themselves. 540 | 541 | ```swift 542 | actor Island { 543 | var flock: [Chicken] // non-Sendable 544 | var food: [Pineapple] // Sendable 545 | } 546 | ``` 547 | 548 | Global-actor-isolated types are also implicitly `Sendable` for similar reasons. 549 | They do not have a private, dedicated isolation domain, but their state is still 550 | protected by an actor. 551 | 552 | ```swift 553 | @MainActor 554 | class ChickenValley { 555 | var flock: [Chicken] // non-Sendable 556 | var food: [Pineapple] // Sendable 557 | } 558 | ``` 559 | 560 | ### Reference Types 561 | 562 | Unlike value types, reference types cannot be implicitly `Sendable`. 563 | And while they can be made `Sendable`, 564 | doing so comes with a number of constraints. 565 | To make a class `Sendable` it must contain no mutable state and all 566 | immutable properties must also be `Sendable`. 567 | Further, the compiler can only validate the implementation of final classes. 568 | 569 | ```swift 570 | final class Chicken: Sendable { 571 | let name: String 572 | } 573 | ``` 574 | 575 | It is possible to satisfy the thread-safety requirements of `Sendable` 576 | using synchronization primitives that the compiler cannot reason about, 577 | such as through OS-specific constructs or 578 | when working with thread-safe types implemented in C/C++/Objective-C. 579 | Such types may be marked as conforming to `@unchecked Sendable` to promise the 580 | compiler that the type is thread-safe. 581 | The compiler will not perform any checking on an `@unchecked Sendable` type, 582 | so this opt-out must be used with caution. 583 | 584 | ### Suspension Points 585 | 586 | A task can switch between isolation domains when a function in one 587 | domain calls a function in another. 588 | A call that crosses an isolation boundary must be made asynchronously, 589 | because the destination isolation domain might be busy running other tasks. 590 | In that case, the task will be suspended until the destination isolation 591 | domain is available. 592 | Critically, a suspension point does _not_ block. 593 | The current isolation domain (and the thread it is running on) 594 | are freed up to perform other work. 595 | The Swift concurrency runtime expects code to never block on future work, 596 | allowing the system to always make forward progress. 597 | This eliminates a common source of deadlocks in concurrent code. 598 | 599 | ```swift 600 | @MainActor 601 | func stockUp() { 602 | // beginning execution on MainActor 603 | let food = Pineapple() 604 | 605 | // switching to the island actor's domain 606 | await island.store(food) 607 | } 608 | ``` 609 | 610 | Potential suspension points are marked in source code with the `await` keyword. 611 | Its presence indicates that the call might suspend at runtime, but `await` does not force a suspension. The function being called might 612 | suspend only under certain dynamic conditions. 613 | It's possible that a call marked with `await` will not actually suspend. 614 | 615 | ### Atomicity 616 | 617 | While actors do guarantee safety from data races, they do not ensure 618 | atomicity across suspension points. 619 | Concurrent code often needs to execute a sequence of operations together as an 620 | atomic unit, such that other threads can never see an intermediate state. 621 | Units of code that require this property are known as _critical sections_. 622 | 623 | Because the current isolation domain is freed up to perform other work, 624 | actor-isolated state may change after an asynchronous call. 625 | As a consequence, you can think of explicitly marking potential suspension 626 | points as a way to indicate the end of a critical section. 627 | 628 | ```swift 629 | func deposit(pineapples: [Pineapple], onto island: Island) async { 630 | var food = await island.food 631 | food += pineapples 632 | await island.store(food) 633 | } 634 | ``` 635 | 636 | This code assumes, incorrectly, that the `island` actor's `food` value will not 637 | change between asynchronous calls. 638 | Critical sections should always be structured to run synchronously. 639 | 640 | > Note: For more information, see the 641 | [Defining and Calling Asynchronous Functions][] section of 642 | The Swift Programming Language. 643 | 644 | [Defining and Calling Asynchronous Functions]: https://docs.swift.org/swift-book/documentation/the-swift-programming-language/concurrency/#Defining-and-Calling-Asynchronous-Functions 645 | -------------------------------------------------------------------------------- /Guide.docc/IncrementalAdoption.md: -------------------------------------------------------------------------------- 1 | # Incremental Adoption 2 | 3 | Learn how you can introduce Swift concurrency features into your project 4 | incrementally. 5 | 6 | Migrating projects towards the Swift 6 language mode is usually done in stages. 7 | In fact, many projects began the process before Swift 6 was even available. 8 | You can continue to introduce concurrency features _gradually_, 9 | addressing any problems that come up along the way. 10 | This allows you to make incremental progress without disrupting the 11 | entire project. 12 | 13 | Swift includes a number of language features and standard library APIs to help 14 | make incremental adoption easier. 15 | 16 | ## Wrapping Callback-Based Functions 17 | 18 | APIs that accept and invoke a single function on completion are an extremely 19 | common pattern in Swift. 20 | It's possible to make a version of such a function that is usable directly from 21 | an asynchronous context. 22 | 23 | ```swift 24 | func updateStyle(backgroundColor: ColorComponents, completionHandler: @escaping () -> Void) { 25 | // ... 26 | } 27 | ``` 28 | 29 | This is an example of a function that informs a client its work is complete 30 | using a callback. 31 | There is no way for a caller to determine when or on what thread the callback 32 | will be invoked without consulting documentation. 33 | 34 | You can wrap this function up into an asynchronous version using 35 | _continuations_. 36 | 37 | ```swift 38 | func updateStyle(backgroundColor: ColorComponents) async { 39 | await withCheckedContinuation { continuation in 40 | updateStyle(backgroundColor: backgroundColor) { 41 | // ... do some work here ... 42 | 43 | continuation.resume() 44 | } 45 | } 46 | } 47 | ``` 48 | 49 | > Note: You have to take care to _resume_ the continuation _exactly once_. 50 | > If you miss invoking it, the calling task will remain suspended indefinitely. 51 | > On the other hand, resuming a checked continuation more than once will cause an expected crash, 52 | > protecting you from undefined behavior. 53 | 54 | With an asynchronous version, there is no longer any ambiguity. 55 | After the function has completed, execution will always resume in the same 56 | context it was started in. 57 | 58 | ```swift 59 | await updateStyle(backgroundColor: color) 60 | // style has been updated 61 | ``` 62 | 63 | The `withCheckedContinuation` function is one of a [suite of standard library 64 | APIs][continuation-apis] that exist to make interfacing non-async and async code possible. 65 | 66 | > Note: Introducing asynchronous code into a project can surface data isolation 67 | checking violations. To understand and address these, see [Crossing Isolation Boundaries][] 68 | 69 | [Crossing Isolation Boundaries]: 70 | [continuation-apis]: https://developer.apple.com/documentation/swift/concurrency#continuations 71 | 72 | ## Dynamic Isolation 73 | 74 | Expressing the isolation of your program statically, using annotations and 75 | other language constructs, is both powerful and concise. 76 | But it can be difficult to introduce static isolation without updating 77 | all dependencies simultaneously. 78 | 79 | Dynamic isolation provides runtime mechanisms you can use as a fallback for 80 | describing data isolation. 81 | It can be an essential tool for interfacing a Swift 6 component 82 | with another that has not yet been updated, 83 | even if these components are within the _same_ module. 84 | 85 | ### Internal-Only Isolation 86 | 87 | Suppose you have determined that a reference type within your project can be 88 | best described with `MainActor` static isolation. 89 | 90 | ```swift 91 | @MainActor 92 | class WindowStyler { 93 | private var backgroundColor: ColorComponents 94 | 95 | func applyStyle() { 96 | // ... 97 | } 98 | } 99 | ``` 100 | 101 | This `MainActor` isolation may be _logically_ correct. 102 | But if this type is used in other unmigrated locations, 103 | adding static isolation here could require many additional changes. 104 | An alternative is to use dynamic isolation to help control the scope. 105 | 106 | ```swift 107 | class WindowStyler { 108 | @MainActor 109 | private var backgroundColor: ColorComponents 110 | 111 | func applyStyle() { 112 | MainActor.assumeIsolated { 113 | // use and interact with other `MainActor` state 114 | } 115 | } 116 | } 117 | ``` 118 | 119 | Here, the isolation has been internalized into the class. 120 | This keeps any changes localized to the type, allowing you make 121 | changes without affecting any clients of the type. 122 | 123 | However, a major disadvantage of this technique is the type's true isolation 124 | requirements remain invisible. 125 | There is no way for clients to determine if or how they should change based on 126 | this public API. 127 | You should use this approach only as a temporary solution, and only when you 128 | have exhausted other options. 129 | 130 | ### Usage-Only Isolation 131 | 132 | If it is impractical to contain isolation exclusively within a type, you can 133 | instead expand the isolation to cover only its API usage. 134 | 135 | To do this, first apply static isolation to the type, 136 | and then use dynamic isolation at any usage locations: 137 | 138 | ```swift 139 | @MainActor 140 | class WindowStyler { 141 | // ... 142 | } 143 | 144 | class UIStyler { 145 | @MainActor 146 | private let windowStyler: WindowStyler 147 | 148 | func applyStyle() { 149 | MainActor.assumeIsolated { 150 | windowStyler.applyStyle() 151 | } 152 | } 153 | } 154 | ``` 155 | 156 | Combining static and dynamic isolation can be a powerful tool to keep the 157 | scope of changes gradual. 158 | 159 | ### Explicit MainActor Context 160 | 161 | The `assumeIsolated` method is synchronous and exists to recover isolation 162 | information from runtime back into the type-system by preventing execution 163 | if the assumption was incorrect. 164 | The `MainActor` type also has a method you can use to manually switch 165 | isolation in an asynchronous context. 166 | 167 | ```swift 168 | // type that should be MainActor, but has not been updated yet 169 | class PersonalTransportation { 170 | } 171 | 172 | await MainActor.run { 173 | // isolated to the MainActor here 174 | let transport = PersonalTransportation() 175 | 176 | // ... 177 | } 178 | ``` 179 | 180 | Remember that static isolation allows the compiler to both verify and automate 181 | the process of switching isolation as needed. 182 | Even when used in combination with static isolation, it can be difficult 183 | to determine when `MainActor.run` is truly necessary. 184 | While `MainActor.run` can be useful during migration, 185 | it should not be used as a substitute for expressing the isolation 186 | requirements of your system statically. 187 | The ultimate goal should still be to apply `@MainActor` 188 | to `PersonalTransportation`. 189 | 190 | ## Missing Annotations 191 | 192 | Dynamic isolation gives you tools to express isolation at runtime. 193 | But you may also find you need to describe other concurrency properties 194 | that are missing from unmigrated modules. 195 | 196 | ### Unmarked Sendable Closures 197 | 198 | The sendability of a closure affects how the compiler infers isolation for its 199 | body. 200 | A callback closure that actually does cross isolation boundaries but is 201 | _missing_ a `Sendable` annotation violates a critical invariant of the 202 | concurrency system. 203 | 204 | ```swift 205 | // definition within a pre-Swift 6 module 206 | extension JPKJetPack { 207 | // Note the lack of a @Sendable annotation 208 | static func jetPackConfiguration(_ callback: @escaping () -> Void) { 209 | // Can potentially cross isolation domains 210 | } 211 | } 212 | 213 | @MainActor 214 | class PersonalTransportation { 215 | func configure() { 216 | JPKJetPack.jetPackConfiguration { 217 | // MainActor isolation will be inferred here 218 | self.applyConfiguration() 219 | } 220 | } 221 | 222 | func applyConfiguration() { 223 | } 224 | } 225 | ``` 226 | 227 | If `jetPackConfiguration` can invoke its closure in another isolation domain, 228 | it must be marked `@Sendable`. 229 | When an un-migrated module hasn't yet done this, it will result in incorrect 230 | actor inference. 231 | This code will compile without issue but crash at runtime. 232 | 233 | > Note: It is not possible for the compiler to detect or diagnose the 234 | _lack_ of compiler-visible information. 235 | 236 | To workaround this, you can manually annotate the closure with `@Sendable.` 237 | This will prevent the compiler from inferring `MainActor` isolation. 238 | Because the compiler now knows actor isolation could change, 239 | it will require a task at the callsite and an await in the task. 240 | 241 | ```swift 242 | @MainActor 243 | class PersonalTransportation { 244 | func configure() { 245 | JPKJetPack.jetPackConfiguration { @Sendable in 246 | // Sendable closures do not infer actor isolation, 247 | // making this context non-isolated 248 | Task { 249 | await self.applyConfiguration() 250 | } 251 | } 252 | } 253 | 254 | func applyConfiguration() { 255 | } 256 | } 257 | ``` 258 | 259 | Alternatively, it is also possible to disable runtime isolation assertions 260 | for the module with the `-disable-dynamic-actor-isolation` compiler flag. 261 | This will suppress all runtime enforcement of dynamic actor isolation. 262 | 263 | > Warning: This flag should be used with caution. 264 | Disabling these runtime checks will permit data isolation violations. 265 | 266 | ## Integrating DispatchSerialQueue with Actors 267 | 268 | By default, the mechanism actors use to schedule and execute work 269 | is system-defined. 270 | However you can override this to provide a custom implementation. 271 | The `DispatchSerialQueue` type includes built-in support for this facility. 272 | 273 | ```swift 274 | actor LandingSite { 275 | private let queue = DispatchSerialQueue(label: "something") 276 | 277 | nonisolated var unownedExecutor: UnownedSerialExecutor { 278 | queue.asUnownedSerialExecutor() 279 | } 280 | 281 | func acceptTransport(_ transport: PersonalTransportation) { 282 | // this function will be running on queue 283 | } 284 | } 285 | ``` 286 | 287 | This can be useful if you want to migrate a type towards the actor model 288 | while maintaining compatibility with code that depends on `DispatchQueue`. 289 | 290 | ## Backwards Compatibility 291 | 292 | It's important to keep in mind that static isolation, being part of the type 293 | system, affects your public API. 294 | But you can migrate your own modules in a way that improves their APIs for 295 | Swift 6 *without* breaking any existing clients. 296 | 297 | Suppose the `WindowStyler` is public API. 298 | You have determined that it really should be `MainActor`-isolated, but want to 299 | ensure backwards compatibility for clients. 300 | 301 | ```swift 302 | @preconcurrency @MainActor 303 | public class WindowStyler { 304 | // ... 305 | } 306 | ``` 307 | 308 | Using `@preconcurrency` this way marks the isolation as conditional on the 309 | client module also having complete checking enabled. 310 | This preserves source compatibility with clients that have not yet begun 311 | adopting Swift 6. 312 | 313 | ## Dependencies 314 | 315 | Often, you aren't in control of the modules you need to import as dependencies. 316 | If these modules have not yet adopted Swift 6, you may find yourself with 317 | errors that are difficult or impossible to resolve. 318 | 319 | There are a number of different kinds of problems that result from using 320 | unmigrated code. 321 | The `@preconcurrency` annotation can help with many of these situations: 322 | 323 | - [Non-Sendable types][] 324 | - Mismatches in [protocol-conformance isolation][] 325 | 326 | [Non-Sendable types]: 327 | [protocol-conformance isolation]: 328 | 329 | ## C/Objective-C 330 | 331 | You can expose Swift concurrency support for your C and Objective-C APIs 332 | using annotations. 333 | This is made possible by Clang's 334 | [concurrency-specific annotations][clang-annotations]: 335 | 336 | [clang-annotations]: https://clang.llvm.org/docs/AttributeReference.html#customizing-swift-import 337 | 338 | ``` 339 | __attribute__((swift_attr(“@Sendable”))) 340 | __attribute__((swift_attr(“@_nonSendable”))) 341 | __attribute__((swift_attr("nonisolated"))) 342 | __attribute__((swift_attr("@UIActor"))) 343 | __attribute__((swift_attr("sending"))) 344 | 345 | __attribute__((swift_async(none))) 346 | __attribute__((swift_async(not_swift_private, COMPLETION_BLOCK_INDEX)) 347 | __attribute__((swift_async(swift_private, COMPLETION_BLOCK_INDEX))) 348 | __attribute__((__swift_async_name__(NAME))) 349 | __attribute__((swift_async_error(none))) 350 | __attribute__((__swift_attr__("@_unavailableFromAsync(message: \"" msg "\")"))) 351 | ``` 352 | 353 | When working with a project that can import Foundation, the following 354 | annotation macros are available in `NSObjCRuntime.h`: 355 | 356 | ``` 357 | NS_SWIFT_SENDABLE 358 | NS_SWIFT_NONSENDABLE 359 | NS_SWIFT_NONISOLATED 360 | NS_SWIFT_UI_ACTOR 361 | NS_SWIFT_SENDING 362 | 363 | NS_SWIFT_DISABLE_ASYNC 364 | NS_SWIFT_ASYNC(COMPLETION_BLOCK_INDEX) 365 | NS_REFINED_FOR_SWIFT_ASYNC(COMPLETION_BLOCK_INDEX) 366 | NS_SWIFT_ASYNC_NAME 367 | NS_SWIFT_ASYNC_NOTHROW 368 | NS_SWIFT_UNAVAILABLE_FROM_ASYNC(msg) 369 | ``` 370 | 371 | ### Dealing with missing isolation annotations in Objective-C libraries 372 | 373 | While the SDKs and other Objective-C libraries make progress in adopting Swift concurrency, 374 | they will often go through the exercise of codifying contracts which were only explained in 375 | documentation. For example, before Swift concurrency, APIs frequently had to document their 376 | threading behavior with comments like "this will always be called on the main thread". 377 | 378 | Swift concurrency enables us to turn these code comments, into compiler and runtime 379 | enforced isolation checks, that Swift will then verify when you adopt such APIs. 380 | 381 | For example, the fictional `NSJetPack` protocol generally invokes all of its delegate methods 382 | on the main thread, and therefore has now become MainActor-isolated. 383 | 384 | The library author can mark as MainActor isolated using the `NS_SWIFT_UI_ACTOR` attribute, 385 | which is equivalent to annotating a type using `@MainActor` in Swift: 386 | 387 | ```swift 388 | NS_SWIFT_UI_ACTOR 389 | @protocol NSJetPack // fictional protocol 390 | // ... 391 | @end 392 | ``` 393 | 394 | Thanks to this, all member methods of this protocol inherit the `@MainActor` isolation, 395 | and for most methods this is correct. 396 | 397 | However, in this example, let us consider a method which was previously documented as follows: 398 | 399 | ```objc 400 | NS_SWIFT_UI_ACTOR // SDK author annotated using MainActor in recent SDK audit 401 | @protocol NSJetPack // fictional protocol 402 | /* Return YES if this jetpack supports flying at really high altitude! 403 | 404 | JetPackKit invokes this method at a variety of times, and not always on the main thread. For example, ... 405 | */ 406 | @property(readonly) BOOL supportsHighAltitude; 407 | 408 | @end 409 | ``` 410 | 411 | This method's isolation was accidentally inferred as `@MainActor`, because of the annotation on the enclosing type. 412 | Although it has specifically documented a different threading strategy - it may or may not 413 | be invoked on the main actor - annotating these semantics on the method was accidentally missed. 414 | 415 | This is an annotation problem in the fictional JetPackKit library. 416 | Specifically, it is missing a `nonisolated` annotation on the method, 417 | which would inform Swift about the correct and expected execution semantics. 418 | 419 | Swift code adopting this library may look like this: 420 | 421 | ```swift 422 | @MainActor 423 | final class MyJetPack: NSJetPack { 424 | override class var supportsHighAltitude: Bool { // runtime crash in Swift 6 mode 425 | true 426 | } 427 | } 428 | ``` 429 | 430 | The above code will crash with a runtime check, which aims to ensure we are actually 431 | executing on the main actor as we're crossing from objective-c's non-swift-concurrency 432 | land into Swift. 433 | 434 | It is a Swift 6 feature to detect such issues automatically and crash at runtime 435 | when such expectations are violated. Leaving such issues un-diagnosed, could lead 436 | to actual hard-to-detect data races, and undermine Swift 6's promise about data-race safety. 437 | 438 | Such failure would include a similar backtrace to this: 439 | 440 | ``` 441 | * thread #5, queue = 'com.apple.root.default-qos', stop reason = EXC_BREAKPOINT (code=1, subcode=0x1004f8a5c) 442 | * frame #0: 0x00000001004..... libdispatch.dylib`_dispatch_assert_queue_fail + 120 443 | frame #1: 0x00000001004..... libdispatch.dylib`dispatch_assert_queue + 196 444 | frame #2: 0x0000000275b..... libswift_Concurrency.dylib`swift_task_isCurrentExecutorImpl(swift::SerialExecutorRef) + 280 445 | frame #3: 0x0000000275b..... libswift_Concurrency.dylib`Swift._checkExpectedExecutor(_filenameStart: Builtin.RawPointer, _filenameLength: Builtin.Word, _filenameIsASCII: Builtin.Int1, _line: Builtin.Word, _executor: Builtin.Executor) -> () + 60 446 | frame #4: 0x00000001089..... MyApp.debug.dylib`@objc static JetPack.supportsHighAltitude.getter at :0 447 | ... 448 | frame #10: 0x00000001005..... libdispatch.dylib`_dispatch_root_queue_drain + 404 449 | frame #11: 0x00000001005..... libdispatch.dylib`_dispatch_worker_thread2 + 188 450 | frame #12: 0x00000001005..... libsystem_pthread.dylib`_pthread_wqthread + 228 451 | ``` 452 | 453 | > Note: When encountering such an issue, and by investigating the documentation and API annotations you determine something 454 | > was incorrectly annotated, the best way to resolve the root cause of the problem is to report the issue back to the 455 | > library maintainer. 456 | 457 | As you can see, the runtime injected an executor check into the call, and the dispatch queue assertion (of it running on the MainActor), 458 | has failed. This prevents sneaky and hard to debug data-races. 459 | 460 | The correct long-term solution to this issue is the library fixing the method's annotation, by marking it as `nonisolated`: 461 | 462 | ```objc 463 | // Solution in the library providing the API: 464 | @property(readonly) BOOL supportsHighAltitude NS_SWIFT_NONISOLATED; 465 | ```` 466 | 467 | Until the library fixes its annotation issue, you are able to witness the method using a correctly `nonisolated` method, like this: 468 | 469 | ```swift 470 | // Solution in adopting client code, wishing to run in Swift 6 mode: 471 | @MainActor 472 | final class MyJetPack: NSJetPack { 473 | // Correct 474 | override nonisolated class var supportsHighAltitude: Bool { 475 | true 476 | } 477 | } 478 | ``` 479 | 480 | This way Swift knows not to check for the not-correct assumption that the method requires main actor isolation. 481 | 482 | -------------------------------------------------------------------------------- /Guide.docc/Info.plist: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | CFBundleDisplayName 6 | Swift 6 Concurrency Migration Guide 7 | CFBundleIdentifier 8 | org.swift.migration.6 9 | CDDefaultModuleKind 10 | 11 | 12 | -------------------------------------------------------------------------------- /Guide.docc/LibraryEvolution.md: -------------------------------------------------------------------------------- 1 | # Library Evolution 2 | 3 | Annotate library APIs for concurrency while preserving source and ABI 4 | compatibility. 5 | 6 | Concurrency annotations such as `@MainActor` and `@Sendable` can impact source 7 | and ABI compatibility. Library authors should be aware of these implications when 8 | annotating existing APIs. 9 | 10 | ## Preconcurrency annotations 11 | 12 | The `@preconcurrency` attribute can be used directly on library APIs to 13 | stage in new concurrency requirements that are checked at compile time 14 | without breaking source or ABI compatibility for clients: 15 | 16 | ```swift 17 | @preconcurrency @MainActor 18 | struct S { ... } 19 | 20 | @preconcurrency 21 | public func performConcurrently( 22 | completion: @escaping @Sendable () -> Void 23 | ) { ... } 24 | ``` 25 | 26 | Clients do not need to use a `@preconcurrency import` for the new errors 27 | to be downgraded. If the clients build with minimal concurrency checking, 28 | errors from `@preconcurrency` APIs will be suppressed. If the clients build 29 | with complete concurrency checking or the Swift 6 language mode, the errors 30 | will be downgraded to warnings. 31 | 32 | For ABI compatibility, `@preconcurrency` will mangle symbol names without any 33 | concurrency annotations. If an API was introduced with some concurrency 34 | annotations, and is later updated to include additional concurrency 35 | annotations, then applying `@preconcurrency` is not sufficient for preserving 36 | mangling. `@_silgen_name` can be used in cases where you need more precise 37 | control over mangling concurrency annotations. 38 | 39 | Note that all APIs imported from C, C++, and Objective-C are automatically 40 | considered `@preconcurrency`. Concurrency attributes can always be applied 41 | to these APIs using `__attribute__((__swift_attr__("")))` 42 | without breaking source or ABI compatibility. 43 | 44 | ## Sendable 45 | 46 | ### Conformances on concrete types 47 | 48 | Adding a `Sendable` conformance to a concrete type, including conditional 49 | conformances, is typically a source compatible change in practice. 50 | 51 | **Source and ABI compatible:** 52 | 53 | ```diff 54 | -public struct S 55 | +public struct S: Sendable 56 | ``` 57 | 58 | Like any other conformance, adding a conformance to `Sendable` can change 59 | overload resolution if the concrete type satisfies more specialized 60 | requirements. However, it's unlikely that an API which overloads on a 61 | `Sendable` conformance would change type inference in a way that breaks 62 | source compatibility or program behavior. 63 | 64 | Adding a `Sendable` conformance to a concrete type, and not one of its type 65 | parameters, is always an ABI compatible change. 66 | 67 | ### Generic requirements 68 | 69 | Adding a `Sendable` conformance requirement to a generic type or function is 70 | a source incompatible change, because it places a restriction on generic 71 | arguments passed by the client. 72 | 73 | **Source and ABI incompatible:** 74 | 75 | ```diff 76 | -public func generic 77 | +public func generic where T: Sendable 78 | ``` 79 | 80 | **To resolve:** Apply `@preconcurrency` to the type or function declaration to 81 | downgrade requirement failures to warnings and preserve ABI: 82 | 83 | ```swift 84 | @preconcurrency 85 | public func generic where T: Sendable { ... } 86 | ``` 87 | 88 | ### Function types 89 | 90 | Like generic requirements, adding `@Sendable` to a function type is a 91 | source and ABI incompatible change: 92 | 93 | **Source and ABI incompatible:** 94 | 95 | ```diff 96 | -public func performConcurrently(completion: @escaping () -> Void) 97 | +public func performConcurrently(completion: @escaping @Sendable () -> Void) 98 | ``` 99 | 100 | **To resolve:** Apply `@preconcurrency` to the enclosing function declaration 101 | to downgrade requirement failures to warnings and preserve ABI: 102 | 103 | ```swift 104 | @preconcurrency 105 | public func performConcurrently(completion: @escaping @Sendable () -> Void) 106 | ``` 107 | 108 | ## Main actor annotations 109 | 110 | ### Protocols and types 111 | 112 | Adding `@MainActor` annotations to protocols or type declarations is a source 113 | and ABI incompatible change. 114 | 115 | **Source and ABI incompatible:** 116 | 117 | ```diff 118 | -public protocol P 119 | +@MainActor public protocol P 120 | 121 | -public class C 122 | +@MainActor public class C 123 | ``` 124 | 125 | Adding `@MainActor` to protocols and type declarations has a wider impact than 126 | other concurrency annotations because the `@MainActor` annotation can be 127 | inferred throughout client code, including protocol conformances, subclasses, 128 | and extension methods. 129 | 130 | Applying `@preconcurrency` to the protocol or type declaration will downgrade 131 | actor isolation errors based on the concurrency checking level. However, 132 | `@preconcurrency` is not sufficient for preserving ABI compatibility for 133 | clients in cases where the `@preconcurrency @MainActor` annotation can be 134 | inferred on other declarations in client code. For example, consider the 135 | following API in a client library: 136 | 137 | ```swift 138 | extension P { 139 | public func onChange(action: @escaping @Sendable () -> Void) 140 | } 141 | ``` 142 | 143 | If `P` is retroactively annotated with `@preconcurrency @MainActor`, these 144 | annotations will be inferred on the extension method. If an extension method is 145 | also part of a library with ABI compatibility constraints, then 146 | `@preconcurrency` will strip all concurrency related annotations from mangling. 147 | This can be worked around in the client library either by applying the 148 | appropriate isolation explicitly, such as: 149 | 150 | ```swift 151 | extension P { 152 | nonisolated public func onChange(action: @escaping @Sendable () -> Void) 153 | } 154 | ``` 155 | 156 | Language affordances for precise control over the ABI of a declaration are 157 | [under development][ABIAttr]. 158 | 159 | [ABIAttr]: https://forums.swift.org/t/pitch-controlling-the-abi-of-a-declaration/75123 160 | 161 | ### Function declarations and types 162 | 163 | Adding `@MainActor` to a function declaration or a function type is a 164 | source and ABI incompatible change. 165 | 166 | **Source and ABI incompatible:** 167 | 168 | ```diff 169 | -public func runOnMain() 170 | +@MainActor public func runOnMain() 171 | 172 | -public func performConcurrently(completion: @escaping () -> Void) 173 | +public func performConcurrently(completion: @escaping @MainActor () -> Void) 174 | ``` 175 | 176 | **To resolve:** Apply `@preconcurrency` to the enclosing function declaration 177 | to downgrade requirement failures to warnings and preserve ABI: 178 | 179 | ```swift 180 | @preconcurrency @MainActor 181 | public func runOnMain() { ... } 182 | 183 | @preconcurrency 184 | public func performConcurrently(completion: @escaping @MainActor () -> Void) { ... } 185 | ``` 186 | 187 | ## `sending` parameters and results 188 | 189 | Adding `sending` to a result lifts restrictions in client code, and is 190 | always a source and ABI compatible change: 191 | 192 | **Source and ABI compatible:** 193 | 194 | ```diff 195 | -public func getValue() -> NotSendable 196 | +public func getValue() -> sending NotSendable 197 | ``` 198 | 199 | However, adding `sending` to a parameter is more restrictive at the caller. 200 | 201 | **Source and ABI incompatible:** 202 | 203 | ```diff 204 | -public func takeValue(_: NotSendable) 205 | +public func takeValue(_: sending NotSendable) 206 | ``` 207 | 208 | There is currently no way to stage in a new `sending` annotation on a parameter 209 | without breaking source compatibility. 210 | 211 | ### Replacing `@Sendable` with `sending` 212 | 213 | Replacing an existing `@Sendable` annotation with `sending` on a closure 214 | parameter is a source compatible, ABI incompatible change. 215 | 216 | **Source compatible, ABI incompatible:** 217 | 218 | ```diff 219 | -public func takeValue(_: @Sendable @escaping () -> Void) 220 | +public func takeValue(_: sending @escaping () -> Void) 221 | ``` 222 | 223 | **To resolve:** Adding `sending` to a parameter changes name mangling, so any 224 | adoption must preserve the mangling using `@_silgen_name`. Adopting `sending` 225 | in parameter position must preserve the ownership convention of parameters. No 226 | additional annotation is necessary if the parameter already has an explicit 227 | ownership modifier. For all functions except initializers, use 228 | `__shared sending` to preserve the ownership convention: 229 | 230 | ```swift 231 | public func takeValue(_: __shared sending NotSendable) 232 | ``` 233 | 234 | For initializers, `sending` preserves the default ownership convention, so it's not 235 | necessary to specify an ownership modifier when adopting `sending` on initializer 236 | parameters: 237 | 238 | ```swift 239 | public class C { 240 | public init(ns: sending NotSendable) 241 | } 242 | ``` 243 | -------------------------------------------------------------------------------- /Guide.docc/MigrationGuide.md: -------------------------------------------------------------------------------- 1 | # Migrating to Swift 6 2 | 3 | @Metadata { 4 | @TechnologyRoot 5 | } 6 | 7 | @Options(scope: global) { 8 | @AutomaticSeeAlso(disabled) 9 | @AutomaticTitleHeading(disabled) 10 | @AutomaticArticleSubheading(disabled) 11 | } 12 | 13 | ## Overview 14 | 15 | Swift's concurrency system, introduced in [Swift 5.5](https://www.swift.org/blog/swift-5.5-released/), 16 | makes asynchronous and parallel code easier to write and understand. 17 | With the Swift 6 language mode, the compiler can now 18 | guarantee that concurrent programs are free of data races. 19 | When enabled, compiler safety checks that were 20 | previously optional become required. 21 | 22 | Adopting the Swift 6 language mode is entirely under your control 23 | on a per-target basis. 24 | Targets that build with previous modes, as well as code in other 25 | languages exposed to Swift, can all interoperate with 26 | modules that have been migrated to the Swift 6 language mode. 27 | 28 | It is possible you have been incrementally adopting concurrency features 29 | as they were introduced. 30 | Or, you may have been waiting for the Swift 6 release to begin using them. 31 | Regardless of where your project is in this process, this guide provides 32 | concepts and practical help to ease the migration. 33 | 34 | You will find articles and code examples here that: 35 | 36 | - Explain the concepts used by Swift's data-race safety model. 37 | - Outline a possible way to get started with migration. 38 | - Show how to enable complete concurrency checking for Swift 5 projects. 39 | - Demonstrate how to enable the Swift 6 language mode. 40 | - Present strategies to resolve common problems. 41 | - Provide techniques for incremental adoption. 42 | 43 | > Important: The Swift 6 language mode is _opt-in_. 44 | Existing projects will not switch to this mode without configuration changes. 45 | > 46 | > There is a distinction between the _compiler version_ and _language mode_. 47 | The Swift 6 compiler supports four distinct language modes: "6", "5", "4.2", 48 | and "4". 49 | 50 | ### Contributing 51 | 52 | This guide is under active development. You can view the source, see 53 | full code examples, and learn about how to contribute in the [repository][]. 54 | We would love your contributions in the form of: 55 | 56 | - Filing [issues][] to cover specific code patterns or additional sections of the guide 57 | - Opening pull requests to improve existing content or add new content 58 | - Reviewing others' [pull requests][] for clarity and correctness of writing and code examples 59 | 60 | For more information, see the [contributing][] document. 61 | 62 | [repository]: https://github.com/apple/swift-migration-guide 63 | [issues]: https://github.com/apple/swift-migration-guide/issues 64 | [pull requests]: https://github.com/apple/swift-migration-guide/pulls 65 | [contributing]: https://github.com/apple/swift-migration-guide/blob/main/CONTRIBUTING.md 66 | 67 | ## Topics 68 | 69 | - 70 | - 71 | - 72 | - 73 | - 74 | - 75 | - 76 | - 77 | 78 | ### Swift Concurrency in Depth 79 | 80 | - 81 | -------------------------------------------------------------------------------- /Guide.docc/MigrationStrategy.md: -------------------------------------------------------------------------------- 1 | # Migration Strategy 2 | 3 | Get started migrating your project to the Swift 6 language mode. 4 | 5 | Enabling complete concurrency checking in a module can yield many data-race 6 | safety issues reported by the compiler. 7 | Hundreds, possibly even thousands of warnings are not uncommon. 8 | When faced with a such a large number of problems, 9 | especially if you are just beginning to learn about Swift's data isolation 10 | model, this can feel insurmountable. 11 | 12 | **Don't panic.** 13 | 14 | Frequently, you'll find yourself making substantial progress with just a few 15 | changes. 16 | And as you do, your mental model of how the Swift concurrency system works 17 | will develop just as rapidly. 18 | 19 | > Important: This guidance should not be interpreted as a recommendation. 20 | You should feel confident about using other approaches. 21 | 22 | ## Strategy 23 | 24 | This document outlines a general strategy that could be a good starting point. 25 | There is no one single approach that will work for all projects. 26 | 27 | The approach has three key steps: 28 | 29 | - Select a module 30 | - Enable stricter checking with Swift 5 31 | - Address warnings 32 | 33 | This process will be inherently _iterative_. 34 | Even a single change in one module can have a large impact on the state of the 35 | project as a whole. 36 | 37 | ## Begin from the Outside 38 | 39 | It can be easier to start with the outer-most root module in a project. 40 | This, by definition, is not a dependency of any other module. 41 | Changes here can only have local effects, making it possible to 42 | keep work contained. 43 | 44 | Your changes do not _need_ to be contained to the module, however. 45 | Dependencies under your control that have [unsafe global state][Global] or 46 | [trivially-`Sendable` types][Sendable] can be the root cause of many warnings 47 | across your project. 48 | These can often be the best things to focus on first. 49 | 50 | [Global]: 51 | [Sendable]: 52 | 53 | ## Use the Swift 5 Language Mode 54 | 55 | You could find it quite challenging to move a project from Swift 5 with no 56 | checking directly to the Swift 6 language mode. 57 | It is possible, instead, to incrementally enable more of the Swift 6 checking 58 | mechanisms while remaining in Swift 5 mode. 59 | This will surface issues only as warnings, 60 | keeping your build and tests functional as you progress. 61 | 62 | To start, enable a single upcoming concurrency feature. 63 | This allows you to focus on one _specific type_ of problem at a time. 64 | 65 | Proposal | Description | Feature Flag 66 | :-----------|-------------|------------- 67 | [SE-0401][] | Remove Actor Isolation Inference caused by Property Wrappers | `DisableOutwardActorInference` 68 | [SE-0412][] | Strict concurrency for global variables | `GlobalConcurrency` 69 | [SE-0418][] | Inferring `Sendable` for methods and key path literals | `InferSendableFromCaptures` 70 | 71 | [SE-0401]: https://github.com/swiftlang/swift-evolution/blob/main/proposals/0401-remove-property-wrapper-isolation.md 72 | [SE-0412]: https://github.com/swiftlang/swift-evolution/blob/main/proposals/0412-strict-concurrency-for-global-variables.md 73 | [SE-0418]: https://github.com/swiftlang/swift-evolution/blob/main/proposals/0418-inferring-sendable-for-methods.md 74 | 75 | These can be enabled independently and in any order. 76 | 77 | After you have addressed issues uncovered by upcoming feature flags, 78 | the next step is to [enable complete checking][CompleteChecking] for the module. 79 | This will turn on all of the compiler's remaining data isolation checks. 80 | 81 | [CompleteChecking]: 82 | 83 | ## Address Warnings 84 | 85 | There is one guiding principle you should use as you investigate 86 | warnings: **express what is true now**. 87 | Resist the urge to refactor your code to address issues. 88 | 89 | You will find it beneficial to minimize the amount of change necessary to 90 | get to a warning-free state with complete concurrency checking. 91 | After that is done, use any unsafe opt-outs you applied as an indication of 92 | follow-on refactoring opportunities to introduce a safer isolation mechanism. 93 | 94 | > Note: To learn more about addressing common problems, see . 95 | 96 | ## Iteration 97 | 98 | At first, you'll likely be employing techniques to disable or workaround 99 | data isolation problems. 100 | Once you feel like you've reached the stopping point for a higher-level module, 101 | target one of its dependencies that has required a workaround. 102 | 103 | You don't have to eliminate all warnings to move on. 104 | Remember that sometimes very minor changes can have a significant impact. 105 | You can always return to a module once one of its dependencies has been 106 | updated. 107 | -------------------------------------------------------------------------------- /Guide.docc/RuntimeBehavior.md: -------------------------------------------------------------------------------- 1 | # Runtime Behavior 2 | 3 | Learn how Swift concurrency runtime semantics differ from other runtimes you may 4 | be familiar with, and familiarize yourself with common patterns to achieve 5 | similar end results in terms of execution semantics. 6 | 7 | Swift's concurrency model with a strong focus on async/await, actors and tasks, 8 | means that some patterns from other libraries or concurrency runtimes don't 9 | translate directly into this new model. In this section, we'll explore common 10 | patterns and differences in runtime behavior to be aware of, and how to address 11 | them while you migrate your code to Swift concurrency. 12 | 13 | ## Limiting concurrency using Task Groups 14 | 15 | Sometimes you may find yourself with a large list of work to be processed. 16 | 17 | While it is possible to just enqueue "all" those work items to a task group like this: 18 | 19 | ```swift 20 | // Potentially wasteful -- perhaps this creates thousands of tasks concurrently (?!) 21 | 22 | let lotsOfWork: [Work] = ... 23 | await withTaskGroup(of: Something.self) { group in 24 | for work in lotsOfWork { 25 | // If this is thousands of items, we may end up creating a lot of tasks here. 26 | group.addTask { 27 | await work.work() 28 | } 29 | } 30 | 31 | for await result in group { 32 | process(result) // process the result somehow, depends on your needs 33 | } 34 | } 35 | ``` 36 | 37 | If you expect to deal with hundreds or thousands of items, it might be inefficient to enqueue them all immediately. 38 | Creating a task (in `addTask`) allocates memory for the task in order to suspend and execute it. 39 | While the amount of memory for each task isn't large, it can be significant when creating thousands of tasks that won't execute immediately. 40 | 41 | When faced with such a situation, you can manually throttle the number of concurrently added tasks in the group, as follows: 42 | 43 | ```swift 44 | let lotsOfWork: [Work] = ... 45 | let maxConcurrentWorkTasks = min(lotsOfWork.count, 10) 46 | assert(maxConcurrentWorkTasks > 0) 47 | 48 | await withTaskGroup(of: Something.self) { group in 49 | var submittedWork = 0 50 | for _ in 0.. Note: For the previous release’s Migration Guide, see [Migrating to Swift 5][swift5]. 10 | 11 | [swift5]: https://www.swift.org/migration-guide-swift5/ 12 | 13 | ## Handling Future Enum Cases 14 | 15 | [SE-0192][]: `NonfrozenEnumExhaustivity` 16 | 17 | Lack of a required `@unknown default` has changed from a warning to an error. 18 | 19 | [SE-0192]: https://github.com/swiftlang/swift-evolution/blob/main/proposals/0192-non-exhaustive-enums.md 20 | 21 | ## Concise magic file names 22 | 23 | [SE-0274][]: `ConciseMagicFile` 24 | 25 | The special expression `#file` has changed to a human-readable string 26 | containing the filename and module name. 27 | 28 | [SE-0274]: https://github.com/swiftlang/swift-evolution/blob/main/proposals/0274-magic-file.md 29 | 30 | ## Forward-scan matching for trailing closures 31 | 32 | [SE-0286][]: `ForwardTrailingClosures` 33 | 34 | Could affect code involving multiple, defaulted closure parameters. 35 | 36 | [SE-0286]: https://github.com/swiftlang/swift-evolution/blob/main/proposals/0286-forward-scan-trailing-closures.md 37 | 38 | ## Incremental migration to concurrency checking 39 | 40 | [SE-0337][]: `StrictConcurrency` 41 | 42 | Will introduce errors for any code that risks data races. 43 | 44 | [SE-0337]: https://github.com/swiftlang/swift-evolution/blob/main/proposals/0337-support-incremental-migration-to-concurrency-checking.md 45 | 46 | > Note: This feature implicitly also enables [`IsolatedDefaultValues`](#Isolated-default-value-expressions), 47 | [`GlobalConcurrency`](#Strict-concurrency-for-global-variables), 48 | and [`RegionBasedIsolation`](#Region-based-Isolation). 49 | 50 | ## Implicitly Opened Existentials 51 | 52 | [SE-0352][]: `ImplicitOpenExistentials` 53 | 54 | Could affect overload resolution for functions that involve both 55 | existentials and generic types. 56 | 57 | [SE-0352]: https://github.com/swiftlang/swift-evolution/blob/main/proposals/0352-implicit-open-existentials.md 58 | 59 | ## Regex Literals 60 | 61 | [SE-0354][]: `BareSlashRegexLiterals` 62 | 63 | Could impact the parsing of code that was previously using a bare slash. 64 | 65 | [SE-0354]: https://github.com/swiftlang/swift-evolution/blob/main/proposals/0354-regex-literals.md 66 | 67 | ## Deprecate @UIApplicationMain and @NSApplicationMain 68 | 69 | [SE-0383][]: `DeprecateApplicationMain` 70 | 71 | Will introduce an error for any code that has not migrated to using `@main`. 72 | 73 | [SE-0383]: https://github.com/swiftlang/swift-evolution/blob/main/proposals/0383-deprecate-uiapplicationmain-and-nsapplicationmain.md 74 | 75 | ## Importing Forward Declared Objective-C Interfaces and Protocols 76 | 77 | [SE-0384][]: `ImportObjcForwardDeclarations` 78 | 79 | Will expose previously-invisible types that could conflict with existing 80 | sources. 81 | 82 | [SE-0384]: https://github.com/swiftlang/swift-evolution/blob/main/proposals/0384-importing-forward-declared-objc-interfaces-and-protocols.md 83 | 84 | ## Remove Actor Isolation Inference caused by Property Wrappers 85 | 86 | [SE-0401][]: `DisableOutwardActorInference` 87 | 88 | Could change the inferred isolation of a type and its members. 89 | 90 | [SE-0401]: https://github.com/swiftlang/swift-evolution/blob/main/proposals/0401-remove-property-wrapper-isolation.md 91 | 92 | ## Isolated default value expressions 93 | 94 | [SE-0411][]: `IsolatedDefaultValues` 95 | 96 | Will introduce errors for code that risks data races. 97 | 98 | [SE-0411]: https://github.com/swiftlang/swift-evolution/blob/main/proposals/0411-isolated-default-values.md 99 | 100 | ## Strict concurrency for global variables 101 | 102 | [SE-0412][]: `GlobalConcurrency` 103 | 104 | Will introduce errors for code that risks data races. 105 | 106 | [SE-0412]: https://github.com/swiftlang/swift-evolution/blob/main/proposals/0412-strict-concurrency-for-global-variables.md 107 | 108 | ## Region based Isolation 109 | 110 | [SE-0414][]: `RegionBasedIsolation` 111 | 112 | Increases the constraints of the `Actor.assumeIsolated` function. 113 | 114 | [SE-0414]: https://github.com/swiftlang/swift-evolution/blob/main/proposals/0414-region-based-isolation.md 115 | 116 | ## Inferring `Sendable` for methods and key path literals 117 | 118 | [SE-0418][]: `InferSendableFromCaptures` 119 | 120 | Could affect overload resolution for functions that differ only by sendability. 121 | 122 | [SE-0418]: https://github.com/swiftlang/swift-evolution/blob/main/proposals/0418-inferring-sendable-for-methods.md 123 | 124 | ## Dynamic actor isolation enforcement from non-strict-concurrency contexts 125 | 126 | [SE-0423][]: `DynamicActorIsolation` 127 | 128 | Introduces new assertions that could affect existing code if the runtime 129 | isolation does not match expectations. 130 | 131 | [SE-0423]: https://github.com/swiftlang/swift-evolution/blob/main/proposals/0423-dynamic-actor-isolation.md 132 | 133 | ## Usability of global-actor-isolated types 134 | 135 | [SE-0434][]: `GlobalActorIsolatedTypesUsability` 136 | 137 | Could affect type inference and overload resolution for functions that are 138 | globally-isolated but not `@Sendable`. 139 | 140 | [SE-0434]: https://github.com/swiftlang/swift-evolution/blob/main/proposals/0434-global-actor-isolated-types-usability.md 141 | -------------------------------------------------------------------------------- /Guide.docc/Swift6Mode.md: -------------------------------------------------------------------------------- 1 | # Enabling The Swift 6 Language Mode 2 | 3 | Guarantee your code is free of data races by enabling the Swift 6 language mode. 4 | 5 | ## Using the Swift compiler 6 | 7 | To enable the Swift 6 language mode when running `swift` or `swiftc` 8 | directly at the command line, pass `-swift-version 6`: 9 | 10 | ``` 11 | ~ swift -swift-version 6 main.swift 12 | ``` 13 | 14 | ## Using SwiftPM 15 | 16 | ### Command-line invocation 17 | 18 | `-swift-version 6` can be passed in a Swift package manager command-line 19 | invocation using the `-Xswiftc` flag: 20 | 21 | ``` 22 | ~ swift build -Xswiftc -swift-version -Xswiftc 6 23 | ~ swift test -Xswiftc -swift-version -Xswiftc 6 24 | ``` 25 | 26 | ### Package manifest 27 | 28 | A `Package.swift` file that uses `swift-tools-version` of `6.0` will enable the Swift 6 language 29 | mode for all targets. You can still set the language mode for the package as a whole using the 30 | `swiftLanguageModes` property of `Package`. However, you can now also change the language mode as 31 | needed on a per-target basis using the new `swiftLanguageMode` build setting: 32 | 33 | ```swift 34 | // swift-tools-version: 6.0 35 | 36 | let package = Package( 37 | name: "MyPackage", 38 | products: [ 39 | // ... 40 | ], 41 | targets: [ 42 | // Uses the default tools language mode (6) 43 | .target( 44 | name: "FullyMigrated", 45 | ), 46 | // Still requires 5 47 | .target( 48 | name: "NotQuiteReadyYet", 49 | swiftSettings: [ 50 | .swiftLanguageMode(.v5) 51 | ] 52 | ) 53 | ] 54 | ) 55 | ``` 56 | 57 | Note that if your package needs to continue supporting earlier Swift toolchain versions and you want 58 | to use per-target `swiftLanguageMode`, you will need to create a version-specific manifest for pre-6 59 | toolchains. For example, if you'd like to continue supporting 5.9 toolchains and up, you could have 60 | one manifest `Package@swift-5.9.swift`: 61 | ```swift 62 | // swift-tools-version: 5.9 63 | 64 | let package = Package( 65 | name: "MyPackage", 66 | products: [ 67 | // ... 68 | ], 69 | targets: [ 70 | .target( 71 | name: "FullyMigrated", 72 | ), 73 | .target( 74 | name: "NotQuiteReadyYet", 75 | ) 76 | ] 77 | ) 78 | ``` 79 | 80 | And another `Package.swift` for Swift toolchains 6.0+: 81 | ```swift 82 | // swift-tools-version: 6.0 83 | 84 | let package = Package( 85 | name: "MyPackage", 86 | products: [ 87 | // ... 88 | ], 89 | targets: [ 90 | // Uses the default tools language mode (6) 91 | .target( 92 | name: "FullyMigrated", 93 | ), 94 | // Still requires 5 95 | .target( 96 | name: "NotQuiteReadyYet", 97 | swiftSettings: [ 98 | .swiftLanguageMode(.v5) 99 | ] 100 | ) 101 | ] 102 | ) 103 | ``` 104 | 105 | If instead you would just like to use Swift 6 language mode when it's available (while still 106 | continuing to support older modes) you can keep a single `Package.swift` and specify the version in 107 | a compatible manner: 108 | ```swift 109 | // swift-tools-version: 5.9 110 | 111 | let package = Package( 112 | name: "MyPackage", 113 | products: [ 114 | // ... 115 | ], 116 | targets: [ 117 | .target( 118 | name: "FullyMigrated", 119 | ), 120 | ], 121 | // `swiftLanguageVersions` and `.version("6")` to support pre 6.0 swift-tools-version. 122 | swiftLanguageVersions: [.version("6"), .v5] 123 | ) 124 | ``` 125 | 126 | 127 | ## Using Xcode 128 | 129 | ### Build Settings 130 | 131 | You can control the language mode for an Xcode project or target by setting 132 | the "Swift Language Version" build setting to "6". 133 | 134 | ### XCConfig 135 | 136 | You can also set the `SWIFT_VERSION` setting to `6` in an xcconfig file: 137 | 138 | ``` 139 | // In a Settings.xcconfig 140 | 141 | SWIFT_VERSION = 6; 142 | ``` 143 | -------------------------------------------------------------------------------- /LICENSE.txt: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | 203 | 204 | 205 | ## Runtime Library Exception to the Apache 2.0 License: ## 206 | 207 | 208 | As an exception, if you use this Software to compile your source code and 209 | portions of this Software are embedded into the binary product as a result, 210 | you may redistribute such product without providing attribution as would 211 | otherwise be required by Sections 4(a), 4(b) and 4(d) of the License. 212 | -------------------------------------------------------------------------------- /Package.swift: -------------------------------------------------------------------------------- 1 | // swift-tools-version: 6.0 2 | 3 | import PackageDescription 4 | 5 | let package = Package( 6 | name: "MigrationGuide", 7 | platforms: [ 8 | .macOS(.v10_15), 9 | .iOS(.v13), 10 | .watchOS(.v6), 11 | .tvOS(.v13), 12 | .macCatalyst(.v13), 13 | .visionOS(.v1), 14 | ], 15 | products: [ 16 | .library( 17 | name: "Library", 18 | targets: ["Library"] 19 | ), 20 | .executable(name: "swift5_examples", targets: ["Swift5Examples"]), 21 | .executable(name: "swift6_examples", targets: ["Swift6Examples"]), 22 | ], 23 | targets: [ 24 | .target( 25 | name: "Library" 26 | ), 27 | .testTarget( 28 | name: "LibraryXCTests", 29 | dependencies: ["ObjCLibrary", "Library"] 30 | ), 31 | .target( 32 | name: "ObjCLibrary", 33 | publicHeadersPath: "." 34 | ), 35 | .executableTarget( 36 | name: "Swift5Examples", 37 | dependencies: ["Library", "ObjCLibrary"], 38 | swiftSettings: [ 39 | .swiftLanguageMode(.v5), 40 | .enableUpcomingFeature("StrictConcurrency"), 41 | ] 42 | ), 43 | .executableTarget( 44 | name: "Swift6Examples", 45 | dependencies: ["Library", "ObjCLibrary"] 46 | ) 47 | ] 48 | ) 49 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # The Swift Concurrency Migration Guide 2 | 3 | This repository contains the source for [The Swift Concurrency Migration Guide][scmg], 4 | which is built using [Swift-DocC][docc]. 5 | 6 | ## Contributing 7 | 8 | See [the contributing guide][contributing] for instructions on contributing 9 | to the Swift Migration Guide. 10 | 11 | ## Building 12 | 13 | Run `docc preview Guide.docc` in this repository's root directory. 14 | 15 | After running DocC, 16 | open the link that `docc` outputs to display a local preview in your browser. 17 | 18 | > Note: 19 | > 20 | > If you installed DocC by downloading a toolchain from Swift.org, 21 | > `docc` is located in `usr/bin/`, 22 | > relative to the installation path of the toolchain. 23 | > Make sure your shell's `PATH` environment variable 24 | > includes that directory. 25 | > 26 | > If you installed DocC by downloading Xcode, 27 | > use `xcrun docc` instead. 28 | 29 | [contributing]: https://github.com/apple/swift-migration-guide/blob/main/CONTRIBUTING.md 30 | [docc]: https://github.com/apple/swift-docc 31 | [conduct]: https://www.swift.org/code-of-conduct 32 | [scmg]: https://www.swift.org/migration/documentation/migrationguide -------------------------------------------------------------------------------- /Sources/Examples/Boundaries.swift: -------------------------------------------------------------------------------- 1 | import Library 2 | 3 | // MARK: Core Example Problem 4 | 5 | /// A `MainActor`-isolated function that accepts non-`Sendable` parameters. 6 | @MainActor 7 | func applyBackground(_ color: ColorComponents) { 8 | } 9 | 10 | #if swift(<6.0) 11 | /// A non-isolated function that accepts non-`Sendable` parameters. 12 | func updateStyle(backgroundColor: ColorComponents) async { 13 | // the `backgroundColor` parameter is being moved from the 14 | // non-isolated domain to the `MainActor` here. 15 | // 16 | // Swift 5 Warning: passing argument of non-sendable type 'ColorComponents' into main actor-isolated context may introduce data races 17 | // Swift 6 Error: sending 'backgroundColor' risks causing data races 18 | await applyBackground(backgroundColor) 19 | } 20 | #endif 21 | 22 | #if swift(>=6.0) 23 | /// A non-isolated function that accepts non-`Sendable` parameters which must be safe to use at callsites. 24 | func sending_updateStyle(backgroundColor: sending ColorComponents) async { 25 | await applyBackground(backgroundColor) 26 | } 27 | #endif 28 | 29 | // MARK: Latent Isolation 30 | 31 | /// MainActor-isolated function that accepts non-`Sendable` parameters. 32 | @MainActor 33 | func isolatedFunction_updateStyle(backgroundColor: ColorComponents) async { 34 | // This is safe because backgroundColor cannot change domains. It also 35 | // now no longer necessary to await the call to `applyBackground`. 36 | applyBackground(backgroundColor) 37 | } 38 | 39 | // MARK: Explicit Sendable 40 | 41 | /// An overload used by `sendable_updateStyle` to match types. 42 | @MainActor 43 | func applyBackground(_ color: SendableColorComponents) { 44 | } 45 | 46 | /// The Sendable variant is safe to pass across isolation domains. 47 | func sendable_updateStyle(backgroundColor: SendableColorComponents) async { 48 | await applyBackground(backgroundColor) 49 | } 50 | 51 | // MARK: Computed Value 52 | 53 | /// A Sendable function is used to compute the value in a different isolation domain. 54 | func computedValue_updateStyle(using backgroundColorProvider: @Sendable () -> ColorComponents) async { 55 | // The Swift 6 compiler can automatically determine this value is 56 | // being transferred in a safe way 57 | let components = backgroundColorProvider() 58 | await applyBackground(components) 59 | } 60 | 61 | #if swift(>=6.0) 62 | /// A function that uses a sending parameter to leverage region-based isolation. 63 | func sendingValue_updateStyle(backgroundColor: sending ColorComponents) async { 64 | await applyBackground(backgroundColor) 65 | } 66 | #endif 67 | 68 | // MARK: Global Isolation 69 | /// An overload used by `globalActorIsolated_updateStyle` to match types. 70 | @MainActor 71 | func applyBackground(_ color: GlobalActorIsolatedColorComponents) { 72 | } 73 | 74 | /// MainActor-isolated function that accepts non-`Sendable` parameters. 75 | @MainActor 76 | func globalActorIsolated_updateStyle(backgroundColor: GlobalActorIsolatedColorComponents) async { 77 | // This is safe because backgroundColor cannot change domains. It also 78 | // now no longer necessary to await the call to `applyBackground`. 79 | applyBackground(backgroundColor) 80 | } 81 | 82 | // MARK: actor isolation 83 | 84 | /// An actor that assumes the responsibility of managing the non-Sendable data. 85 | actor Style { 86 | private var background: ColorComponents 87 | 88 | init(background: ColorComponents) { 89 | self.background = background 90 | } 91 | 92 | func applyBackground() { 93 | // make use of background here 94 | } 95 | } 96 | 97 | // MARK: Manual Synchronization 98 | 99 | extension RetroactiveColorComponents: @retroactive @unchecked Sendable { 100 | } 101 | 102 | /// An overload used by `retroactive_updateStyle` to match types. 103 | @MainActor 104 | func applyBackground(_ color: RetroactiveColorComponents ) { 105 | } 106 | 107 | /// A non-isolated function that accepts retroactively-`Sendable` parameters. 108 | func retroactive_updateStyle(backgroundColor: RetroactiveColorComponents) async { 109 | await applyBackground(backgroundColor) 110 | } 111 | 112 | func exerciseBoundaryCrossingExamples() async { 113 | print("Isolation Boundary Crossing Examples") 114 | 115 | #if swift(<6.0) 116 | print(" - updateStyle(backgroundColor:) passing its argument unsafely") 117 | #endif 118 | 119 | #if swift(>=6.0) 120 | print(" - using sending to allow safe usage of ColorComponents") 121 | let nonSendableComponents = ColorComponents() 122 | 123 | await sending_updateStyle(backgroundColor: nonSendableComponents) 124 | #endif 125 | 126 | print(" - using ColorComponents only from the main actor") 127 | let t1 = Task { @MainActor in 128 | let components = ColorComponents() 129 | 130 | await isolatedFunction_updateStyle(backgroundColor: components) 131 | } 132 | 133 | await t1.value 134 | 135 | print(" - using preconcurrency_updateStyle to deal with non-Sendable argument") 136 | 137 | print(" - using a Sendable closure to defer creation") 138 | await computedValue_updateStyle(using: { 139 | ColorComponents() 140 | }) 141 | 142 | #if swift(>=6.0) 143 | print(" - enable region-based isolation with a sending argument") 144 | let capturableComponents = ColorComponents() 145 | 146 | await sendingValue_updateStyle(backgroundColor: capturableComponents) 147 | #endif 148 | 149 | print(" - using a globally-isolated type") 150 | let components = await GlobalActorIsolatedColorComponents() 151 | 152 | await globalActorIsolated_updateStyle(backgroundColor: components) 153 | 154 | print(" - using an actor") 155 | let actorComponents = ColorComponents() 156 | 157 | let actor = Style(background: actorComponents) 158 | 159 | await actor.applyBackground() 160 | 161 | print(" - using a retroactive unchecked Sendable argument") 162 | let retroactiveComponents = RetroactiveColorComponents() 163 | 164 | await retroactive_updateStyle(backgroundColor: retroactiveComponents) 165 | } 166 | -------------------------------------------------------------------------------- /Sources/Examples/ConformanceMismatches.swift: -------------------------------------------------------------------------------- 1 | import Library 2 | 3 | // MARK: Under-Specified Protocol 4 | 5 | #if swift(<6.0) 6 | /// A conforming type that has now adopted global isolation. 7 | @MainActor 8 | class WindowStyler: Styler { 9 | // Swift 5 Warning: main actor-isolated instance method 'applyStyle()' cannot be used to satisfy nonisolated protocol requirement 10 | // Swift 6 Error: main actor-isolated instance method 'applyStyle()' cannot be used to satisfy nonisolated protocol requirement 11 | func applyStyle() { 12 | } 13 | } 14 | #endif 15 | 16 | // MARK: Globally-Isolated Protocol 17 | 18 | /// A type conforming to the global actor annotated `GloballyIsolatedStyler` protocol, 19 | /// will infer the protocol's global actor isolation. 20 | class GloballyIsolatedWindowStyler: GloballyIsolatedStyler { 21 | func applyStyle() { 22 | } 23 | } 24 | 25 | /// A type conforming to `PerRequirementIsolatedStyler` which has MainActor isolated protocol requirements, 26 | /// will infer the protocol's requirements isolation for methods witnessing those protocol requirements *only* 27 | /// for the satisfying methods. 28 | class PerRequirementIsolatedWindowStyler: PerRequirementIsolatedStyler { 29 | func applyStyle() { 30 | // only this is MainActor-isolated 31 | } 32 | 33 | func checkStyle() { 34 | // this method is non-isolated; it is not witnessing any isolated protocol requirement 35 | } 36 | } 37 | 38 | // MARK: Asynchronous Requirements 39 | 40 | /// A conforming type that can have arbitrary isolation and 41 | /// still matches the async requirement. 42 | class AsyncWindowStyler: AsyncStyler { 43 | func applyStyle() { 44 | } 45 | } 46 | 47 | // MARK: Using preconcurrency 48 | 49 | /// A conforming type that will infer the protocol's global isolation *but* 50 | /// with downgraded diagnostics in Swift 6 mode and Swift 5 + complete checking 51 | class StagedGloballyIsolatedWindowStyler: StagedGloballyIsolatedStyler { 52 | func applyStyle() { 53 | } 54 | } 55 | 56 | // MARK: Using Dynamic Isolation 57 | 58 | /// A conforming type that uses a nonisolated function to match 59 | /// with dynamic isolation in the method body. 60 | @MainActor 61 | class DynamicallyIsolatedStyler: Styler { 62 | nonisolated func applyStyle() { 63 | MainActor.assumeIsolated { 64 | // MainActor state is available here 65 | } 66 | } 67 | } 68 | 69 | /// A conforming type that uses a preconcurency conformance, which 70 | /// is a safer and more ergonomic version of DynamicallyIsolatedStyler. 71 | @MainActor 72 | class PreconcurrencyConformanceStyler: @preconcurrency Styler { 73 | func applyStyle() { 74 | } 75 | } 76 | 77 | // MARK: Non-Isolated 78 | 79 | /// A conforming type that uses nonisolated and non-Sendable types but 80 | /// still performs useful work. 81 | @MainActor 82 | class NonisolatedWindowStyler: StylerConfiguration { 83 | nonisolated var primaryColorComponents: ColorComponents { 84 | ColorComponents(red: 0.2, green: 0.3, blue: 0.4) 85 | } 86 | } 87 | 88 | // MARK: Conformance by Proxy 89 | 90 | /// An intermediary type that conforms to the protocol so it can be 91 | /// used by an actor 92 | struct CustomWindowStyle: Styler { 93 | func applyStyle() { 94 | } 95 | } 96 | 97 | /// An actor that interacts with the Style protocol indirectly. 98 | actor ActorWindowStyler { 99 | private let internalStyle = CustomWindowStyle() 100 | 101 | func applyStyle() { 102 | // forward the call through to the conforming type 103 | internalStyle.applyStyle() 104 | } 105 | } 106 | 107 | func exerciseConformanceMismatchExamples() async { 108 | print("Protocol Conformance Isolation Mismatch Examples") 109 | 110 | // Could also all be done with async calls, but this 111 | // makes the isolation, and the ability to invoke them 112 | // from a synchronous context explicit. 113 | await MainActor.run { 114 | #if swift(<6.0) 115 | print(" - using a mismatched conformance") 116 | WindowStyler().applyStyle() 117 | #endif 118 | 119 | print(" - using a MainActor-isolated type") 120 | GloballyIsolatedWindowStyler().applyStyle() 121 | 122 | print(" - using a per-requirement MainActor-isolated type") 123 | PerRequirementIsolatedWindowStyler().applyStyle() 124 | 125 | print(" - using an async conformance") 126 | AsyncWindowStyler().applyStyle() 127 | 128 | print(" - using staged isolation") 129 | StagedGloballyIsolatedWindowStyler().applyStyle() 130 | 131 | print(" - using dynamic isolation") 132 | DynamicallyIsolatedStyler().applyStyle() 133 | 134 | print(" - using a preconcurrency conformance") 135 | PreconcurrencyConformanceStyler().applyStyle() 136 | 137 | let value = NonisolatedWindowStyler().primaryColorComponents 138 | print(" - accessing a non-isolated conformance: ", value) 139 | } 140 | 141 | print(" - using an actor with a proxy conformance") 142 | await ActorWindowStyler().applyStyle() 143 | } 144 | -------------------------------------------------------------------------------- /Sources/Examples/DispatchQueue+PendingWork.swift: -------------------------------------------------------------------------------- 1 | import Dispatch 2 | 3 | extension DispatchQueue { 4 | /// Returns once any pending work has been completed. 5 | func pendingWorkComplete() async { 6 | // TODO: update to withCheckedContinuation https://github.com/apple/swift/issues/74206 7 | await withUnsafeContinuation { continuation in 8 | self.async(flags: .barrier) { 9 | continuation.resume() 10 | } 11 | } 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /Sources/Examples/Globals.swift: -------------------------------------------------------------------------------- 1 | import Dispatch 2 | 3 | #if swift(<6.0) 4 | /// An unsafe global variable. 5 | /// 6 | /// See swift-6-concurrency-migration-guide/commonproblems/#Sendable-Types 7 | var supportedStyleCount = 42 8 | #endif 9 | 10 | /// Version of `supportedStyleCount` that uses global-actor isolation. 11 | @MainActor 12 | var globallyIsolated_supportedStyleCount = 42 13 | 14 | /// Version of `supportedStyleCount` that uses immutability. 15 | let constant_supportedStyleCount = 42 16 | 17 | /// Version of `supportedStyleCount` that uses a computed property. 18 | var computed_supportedStyleCount: Int { 19 | 42 20 | } 21 | 22 | /// Version of `supportedStyleCount` that uses manual synchronization via `sharedQueue` 23 | nonisolated(unsafe) var queueProtected_supportedStyleCount = 42 24 | 25 | /// A non-isolated async function used to exercise all of the global mutable state examples. 26 | func exerciseGlobalExamples() async { 27 | print("Global Variable Examples") 28 | #if swift(<6.0) 29 | // Here is how we access `supportedStyleCount` concurrently in an unsafe way 30 | for _ in 0..<10 { 31 | DispatchQueue.global().async { 32 | supportedStyleCount += 1 33 | } 34 | } 35 | 36 | print(" - accessing supportedStyleCount unsafely:", supportedStyleCount) 37 | 38 | await DispatchQueue.global().pendingWorkComplete() 39 | #endif 40 | 41 | print(" - accessing globallyIsolated_supportedStyleCount") 42 | // establish a MainActor context to access the globally-isolated version 43 | await MainActor.run { 44 | globallyIsolated_supportedStyleCount += 1 45 | } 46 | 47 | // freely access the immutable version from any isolation domain 48 | print(" - accessing constant_supportedStyleCount when non-isolated: ", constant_supportedStyleCount) 49 | 50 | await MainActor.run { 51 | print(" - accessing constant_supportedStyleCount from MainActor: ", constant_supportedStyleCount) 52 | } 53 | 54 | // freely access the computed property from any isolation domain 55 | print(" - accessing computed_supportedStyleCount when non-isolated: ", computed_supportedStyleCount) 56 | 57 | // access the manually-synchronized version... carefully 58 | manualSerialQueue.async { 59 | queueProtected_supportedStyleCount += 1 60 | } 61 | 62 | manualSerialQueue.async { 63 | print(" - accessing queueProtected_supportedStyleCount: ", queueProtected_supportedStyleCount) 64 | } 65 | 66 | await manualSerialQueue.pendingWorkComplete() 67 | } 68 | -------------------------------------------------------------------------------- /Sources/Examples/IncrementalMigration.swift: -------------------------------------------------------------------------------- 1 | import Dispatch 2 | import ObjCLibrary 3 | 4 | /// Example that backs an actor with a queue. 5 | /// 6 | /// > Note: `DispatchSerialQueue`'s initializer was only made available in more recent OS versions. 7 | @available(macOS 14.0, iOS 17.0, macCatalyst 17.0, tvOS 17.0, watchOS 10.0, *) 8 | actor LandingSite { 9 | private let queue = DispatchSerialQueue(label: "SerialQueue") 10 | 11 | // this currently failed to build because of the @available usage, rdar://116684282 12 | // nonisolated var unownedExecutor: UnownedSerialExecutor { 13 | // queue.asUnownedSerialExecutor() 14 | // } 15 | 16 | func acceptTransport(_ transport: JPKJetPack) { 17 | // this function will be running on queue 18 | } 19 | } 20 | 21 | func exerciseIncrementalMigrationExamples() async { 22 | print("Incremental Migration Examples") 23 | 24 | if #available(macOS 14.0, iOS 17.0, macCatalyst 17.0, tvOS 17.0, watchOS 10.0, *) { 25 | print(" - using an actor with a DispatchSerialQueue executor") 26 | let site = LandingSite() 27 | 28 | let transport = JPKJetPack() 29 | 30 | await site.acceptTransport(transport) 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /Sources/Examples/PreconcurrencyImport.swift: -------------------------------------------------------------------------------- 1 | @preconcurrency import Library 2 | 3 | /// A non-isolated function that accepts non-`Sendable` parameters. 4 | func preconcurrency_updateStyle(backgroundColor: ColorComponents) async { 5 | // Swift 5: no diagnostics 6 | // Swift 6 Warning: sending 'backgroundColor' risks causing data races 7 | await applyBackground(backgroundColor) 8 | } 9 | -------------------------------------------------------------------------------- /Sources/Examples/main.swift: -------------------------------------------------------------------------------- 1 | import Dispatch 2 | 3 | /// A Serial queue uses for manual synchronization 4 | let manualSerialQueue = DispatchQueue(label: "com.apple.SwiftMigrationGuide") 5 | 6 | // Note: top-level code provides an asynchronous MainActor-isolated context 7 | await exerciseGlobalExamples() 8 | await exerciseBoundaryCrossingExamples() 9 | await exerciseConformanceMismatchExamples() 10 | await exerciseIncrementalMigrationExamples() 11 | -------------------------------------------------------------------------------- /Sources/Library/Library.swift: -------------------------------------------------------------------------------- 1 | import Foundation 2 | 3 | /// An example of a struct with only `Sendable` properties. 4 | /// 5 | /// This type is **not** Sendable because it is public. If we want a public type to be `Sendable`, we must annotate it explicitly. 6 | public struct ColorComponents { 7 | public let red: Float 8 | public let green: Float 9 | public let blue: Float 10 | 11 | public init(red: Float, green: Float, blue: Float) { 12 | self.red = red 13 | self.green = green 14 | self.blue = blue 15 | } 16 | 17 | public init() { 18 | self.red = 1.0 19 | self.green = 1.0 20 | self.blue = 1.0 21 | } 22 | } 23 | 24 | /// A variant of `ColorComponents` that could be marked as Sendable 25 | public struct RetroactiveColorComponents { 26 | public let red: Float = 1.0 27 | public let green: Float = 1.0 28 | public let blue: Float = 1.0 29 | 30 | public init() {} 31 | } 32 | 33 | /// Explicitly-Sendable variant of `ColorComponents`. 34 | public struct SendableColorComponents : Sendable { 35 | public let red: Float = 1.0 36 | public let green: Float = 1.0 37 | public let blue: Float = 1.0 38 | 39 | public init() {} 40 | } 41 | 42 | @MainActor 43 | public struct GlobalActorIsolatedColorComponents : Sendable { 44 | public let red: Float = 1.0 45 | public let green: Float = 1.0 46 | public let blue: Float = 1.0 47 | 48 | public init() {} 49 | } 50 | 51 | public protocol Styler { 52 | func applyStyle() 53 | } 54 | 55 | @MainActor 56 | public protocol GloballyIsolatedStyler { 57 | func applyStyle() 58 | } 59 | 60 | public protocol PerRequirementIsolatedStyler { 61 | @MainActor 62 | func applyStyle() 63 | } 64 | 65 | @preconcurrency @MainActor 66 | public protocol StagedGloballyIsolatedStyler { 67 | func applyStyle() 68 | } 69 | 70 | public protocol AsyncStyler { 71 | func applyStyle() async 72 | } 73 | 74 | open class UIStyler { 75 | } 76 | 77 | public protocol InheritingStyler: UIStyler { 78 | func applyStyle() 79 | } 80 | 81 | public protocol StylerConfiguration { 82 | var primaryColorComponents: ColorComponents { get } 83 | } 84 | -------------------------------------------------------------------------------- /Sources/ObjCLibrary/JPKJetPack.h: -------------------------------------------------------------------------------- 1 | #import 2 | 3 | NS_ASSUME_NONNULL_BEGIN 4 | 5 | @interface JPKJetPack : NSObject 6 | 7 | /// Disable async to show how completion handlers work explicitly. 8 | + (void)jetPackConfiguration:(void (NS_SWIFT_SENDABLE ^)(void))completionHandler NS_SWIFT_DISABLE_ASYNC; 9 | 10 | @end 11 | 12 | NS_ASSUME_NONNULL_END 13 | -------------------------------------------------------------------------------- /Sources/ObjCLibrary/JPKJetPack.m: -------------------------------------------------------------------------------- 1 | #import "JPKJetPack.h" 2 | 3 | @implementation JPKJetPack 4 | 5 | + (void)jetPackConfiguration:(void (^)(void))completionHandler { 6 | dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ 7 | completionHandler(); 8 | }); 9 | } 10 | 11 | @end 12 | -------------------------------------------------------------------------------- /Sources/ObjCLibrary/ObjCLibrary.h: -------------------------------------------------------------------------------- 1 | @import Foundation; 2 | 3 | @interface OCMPattern : NSObject 4 | 5 | @end 6 | 7 | NS_SWIFT_UI_ACTOR 8 | @interface PCMPatternStore : NSObject 9 | 10 | @end 11 | 12 | #import "JPKJetPack.h" 13 | -------------------------------------------------------------------------------- /Sources/ObjCLibrary/ObjCLibrary.m: -------------------------------------------------------------------------------- 1 | #import 2 | 3 | #import "ObjCLibrary.h" 4 | 5 | @implementation OCMPattern 6 | 7 | @end 8 | 9 | @implementation PCMPatternStore 10 | 11 | @end 12 | -------------------------------------------------------------------------------- /Sources/Swift5Examples: -------------------------------------------------------------------------------- 1 | Examples -------------------------------------------------------------------------------- /Sources/Swift6Examples: -------------------------------------------------------------------------------- 1 | Examples -------------------------------------------------------------------------------- /Tests/Library/LibraryTests.swift: -------------------------------------------------------------------------------- 1 | import Library 2 | import ObjCLibrary 3 | import Testing 4 | 5 | struct LibraryTest { 6 | @Test func testNonIsolated() throws { 7 | let color = ColorComponents() 8 | 9 | #expect(color.red == 1.0) 10 | } 11 | 12 | @MainActor 13 | @Test func testIsolated() throws { 14 | let color = GlobalActorIsolatedColorComponents() 15 | 16 | #expect(color.red == 1.0) 17 | } 18 | 19 | @Test func testNonIsolatedWithGlobalActorIsolatedType() async throws { 20 | let color = await GlobalActorIsolatedColorComponents() 21 | 22 | await #expect(color.red == 1.0) 23 | } 24 | } 25 | 26 | extension LibraryTest { 27 | @Test func testCallbackOperation() async { 28 | await confirmation() { completion in 29 | // function explicitly opts out of an generated async version 30 | // so it requires a continuation here 31 | await withCheckedContinuation { continuation in 32 | JPKJetPack.jetPackConfiguration { 33 | completion() 34 | continuation.resume() 35 | } 36 | } 37 | } 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /Tests/Library/LibraryXCTests.swift: -------------------------------------------------------------------------------- 1 | import ObjCLibrary 2 | import Library 3 | import XCTest 4 | 5 | final class LibraryXCTests: XCTestCase { 6 | func testNonIsolated() throws { 7 | let color = ColorComponents() 8 | 9 | XCTAssertEqual(color.red, 1.0) 10 | } 11 | 12 | @MainActor 13 | func testIsolated() throws { 14 | let color = GlobalActorIsolatedColorComponents() 15 | 16 | XCTAssertEqual(color.red, 1.0) 17 | } 18 | 19 | func testNonIsolatedWithGlobalActorIsolatedType() async throws { 20 | let color = await GlobalActorIsolatedColorComponents() 21 | let redComponent = await color.red 22 | 23 | XCTAssertEqual(redComponent, 1.0) 24 | } 25 | } 26 | 27 | extension LibraryXCTests { 28 | func testCallbackOperation() async { 29 | let exp = expectation(description: "config callback") 30 | 31 | JPKJetPack.jetPackConfiguration { 32 | exp.fulfill() 33 | } 34 | 35 | await fulfillment(of: [exp]) 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /bin/local.sh: -------------------------------------------------------------------------------- 1 | set -euxo pipefail 2 | 3 | export DOCC_JSON_PRETTYPRINT="YES" 4 | 5 | output="./migration-guide" 6 | 7 | xcrun docc convert --experimental-enable-custom-templates --output-path ./migration-guide Guide.docc 8 | 9 | pushd migration-guide 10 | 11 | ruby -run -e httpd -- . -p 8000 12 | -------------------------------------------------------------------------------- /bin/publish.sh: -------------------------------------------------------------------------------- 1 | #! /bin/bash 2 | 3 | set -euxo pipefail 4 | 5 | export DOCC_JSON_PRETTYPRINT="YES" 6 | 7 | output="./migration-guide" 8 | 9 | docc convert \ 10 | --experimental-enable-custom-templates \ 11 | --hosting-base-path migration-guide \ 12 | --output-path "$output" \ 13 | MigrationGuide.docc -------------------------------------------------------------------------------- /bin/redirects/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | The Swift Concurrency Migration Guide: Redirect 4 | 5 | 6 | 7 |
8 | This content has moved; redirecting to the 9 | new location. 10 | 16 |
17 | 25 | 26 | 27 | --------------------------------------------------------------------------------