Skip to content
Tutorials Center
My learning

Topics

Lesson 115 of 146 ยท Advanced Swift

Swift Language Versions and Evolution

Understand Swift releases from 5.0 to 6.3: toolchain versus language mode, Swift 6 data-race safety, upcoming features, version checks and the evolution process.

Swift is a young language that changes every year. A new compiler ships roughly twice a year, and each release adds features, tightens rules, and sometimes deprecates older habits. If you search for Swift help you will find code written for Swift 3, 4, 5 and 6, and the answers do not always agree. To read that code, and to know what is safe to use in your own project, you need a mental map of how Swift versions work.

This lesson gives you that map. You will learn the difference between a toolchain version and a language mode, what changed from Swift 5 to Swift 6.3, why the move to Swift 6 mode is the biggest shift since Swift 3, how to write code that adapts to the compiler version, and how new features are proposed and accepted in the open. Everything that can run on the site's runner (Swift 6.3.2 in Swift 6 language mode) is runnable; build-system settings are read-only.

Two different version numbers

When people say "Swift 6" they might mean two things:

  • The compiler and toolchain version, such as 6.0, 6.1, 6.2 or 6.3. It is what swiftc --version reports. Newer toolchains add language features, library APIs and better diagnostics.
  • The language mode, which is -swift-version 5 or -swift-version 6 (plus older legacy modes). It decides how strict the compiler is about certain rules. A Swift 6.3 compiler can compile your project in Swift 5 mode, and that is the default for existing projects, so upgrading the compiler does not break your code.

The runner compiles every example with swiftc -swift-version 6 -O, so it is a 6.3 compiler in Swift 6 mode. You can ask the compiler about both numbers with conditional compilation. #if compiler(>=X) tests the compiler version, #if swift(>=X) tests the language mode's version, and #if hasFeature(Name) tests whether a particular (often upcoming or experimental) feature is switched on:

Swift Asking the compiler which version it is

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

On the runner you will see language mode is 6.0 or newer, compiler is 6.3 or newer, compiler is older than 6.4, both conditions hold, StrictConcurrency is on, then ExistentialAny is off, MemberImportVisibility is off and the @retroactive attribute exists. Those lines tell a story: Swift 6 mode switches strict concurrency checking on, while features marked upcoming stay off until you ask for them.

The #if compiler and #if swift blocks are how libraries support several compilers at once: code inside a false branch is parsed loosely but never type checked, so a block can use syntax that an old compiler does not know. Wrap newer syntax in #if compiler(>=6.2) and fall back in the #else branch.

A map of the releases

Here is the short history from Swift 5 on, with the features that changed how people write Swift. Each of these has its own lesson in this tutorial.

Version Year Headline additions
5.0 2019 ABI stability on Apple platforms, the Result type, raw strings
5.1 2019 Opaque return types (some), property wrappers, implicit return
5.2 2020 callAsFunction, key paths as functions
5.3 2020 Multiple trailing closures, @main, synthesized Comparable for enums
5.4 2021 Result builders, local functions with overloads
5.5 2021 async/await, actors, structured concurrency, Sendable
5.7 2022 Regex literals and RegexBuilder, if let x shorthand, some in parameters, any for existentials
5.9 2023 Macros, if and switch expressions, parameter packs, noncopyable types (first form), Observation
5.10 2024 Full data-isolation checking available as an opt-in
6.0 2024 Swift 6 language mode with compile-time data-race safety, typed throws, Int128, count(where:), Swift Testing
6.1 2025 Trailing commas in more places, further concurrency refinements
6.2 2025 Approachable concurrency, @concurrent, InlineArray, Span, task names
6.3 2026 The toolchain used on this site (6.3.2)

Release notes are the authoritative source for exact details, and Apple's marketing names (for example "Swift 6.2") track the toolchain. Use the table to orient yourself, and check the official release notes before you depend on a specific version for a feature.

Some of the newer additions are small enough to try right now. Each one only compiles with a recent toolchain, so this is a good way to feel what "Swift 6.x" means:

Swift Library and syntax additions from Swift 6.x

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The program prints the largest Int128, then true, then 1267650600228229401496703205376 (that is 2 to the power of 100, which does not fit in 64 bits), 3, 3, 20 3 and 3 1. InlineArray stores its three elements directly in the value instead of allocating a heap buffer, and Span gives bounds-checked access to contiguous memory without pointers; both are part of the push toward safe, fast low-level code that you will meet again in Unsafe Swift.

Older features you studied earlier also needed a minimum version, and the compiler tells you when you use them too early. A last sampler pulls together features from Swift 5.7 to 6.0:

Swift Features from Swift 5.7 to 6.0 side by side

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The output is closed 7, 3, bad, 10 20, one, 42 and worker. You can read the comments as a checklist of "what do I need a newer compiler for". Note how catch gets a concrete ParseError thanks to typed throws; before 6.0, it was always any Error.

Swift 6 language mode: data-race safety

The most significant change of the modern era is not a single feature but a rule change. In Swift 6 language mode, the compiler proves at compile time that your program has no data races, meaning no two threads can access the same mutable memory at once without synchronization. Shared mutable state must be protected by an actor, confined to the main actor, or made Sendable. Code that Swift 5 accepted with a warning (or without one) can become an error.

You saw the rules in Sendable and Data Races. Here are two typical diagnostics from the runner. First, plain global state in main.swift, touched from an async function:

Swift Global mutable state in Swift 6 mode (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The compiler stops with error: main actor-isolated var 'counter' can not be mutated from a nonisolated context and a note, consider declaring an isolated method on 'MainActor' to perform the mutation. Top-level variables in main.swift are isolated to the main actor in Swift 6 mode, and bump() is nonisolated, so its access is a potential race. There are two honest fixes. You can move the work onto the same actor:

Swift Fix 1: put the function on the main actor

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

or make the shared state an actor, which serializes access by itself:

Swift Fix 2: protect the state with an actor

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

Both programs print 3, deterministically, whichever thread each child task runs on. The second diagnostic is about sharing a class instance between tasks:

Swift Sharing a non-Sendable class (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

You get error: sending value of non-Sendable type '() async -> ()' risks causing data races, with a note on the last increment: access can happen concurrently. The compiler noticed that the detached task and the caller both touch box. Remove the second access, or make Box an actor, or make the data a value type, and the error disappears. Without the later use, the very same capture compiles: Swift's region-based isolation (introduced with Swift 6) allows transferring a value into a task when it is no longer used afterwards.

Migrating a project

Because the language mode is a per-module setting, you do not have to convert everything at once. A safe path, step by step, is:

  1. Move to a Swift 6 toolchain first, staying in Swift 5 mode. Fix the new deprecation warnings.
  2. Turn on strict concurrency checking in Swift 5 mode (-strict-concurrency=complete, or the StrictConcurrency setting). The compiler now reports data-race problems as warnings.
  3. Fix the warnings module by module, starting with the leaf modules that depend on nothing else.
  4. Switch the module to Swift 6 mode. The warnings are now errors, so regressions are caught.
  5. Repeat for the rest of the project. Third-party libraries that are not ready can be imported with @preconcurrency import.

In a Swift package, the language mode and individual features are set in Package.swift (read-only example, since SwiftPM is not on the runner):

Swift
// read-only example: Package.swift
// swift-tools-version: 6.0
import PackageDescription

let package = Package(
    name: "App",
    targets: [
        .target(
            name: "Core",
            swiftSettings: [
                .swiftLanguageMode(.v6),                       // Swift 6 mode (default with tools version 6.0)
                .enableUpcomingFeature("ExistentialAny"),      // opt in early to a future default
            ]
        ),
        .target(
            name: "LegacyBits",
            swiftSettings: [.swiftLanguageMode(.v5)]           // not migrated yet
        ),
    ]
)

On the command line, the same switches look like swiftc -swift-version 6 main.swift or swiftc -swift-version 5 -enable-upcoming-feature ExistentialAny main.swift.

Upcoming and experimental features

New behavior that would break existing code is not simply switched on in Swift 5 mode. The community instead ships it as an upcoming feature, a named flag you enable early. When a language mode changes, some upcoming features become the default: the data-isolation checks are an example, and they are the reason StrictConcurrency reported on in the first example of this lesson. Others stay optional even in Swift 6 mode. ExistentialAny (requiring the any keyword on protocol types) and MemberImportVisibility (an import only makes the members of that module visible in the current file) both reported off there. You can always ask #if hasFeature(...) instead of guessing.

Experimental features are different: they are unfinished, are enabled with -enable-experimental-feature, and may change or disappear. Do not ship production code that relies on them.

A related facility is availability. @available and if #available handle differences in the operating system version, which matters on Apple platforms where a new API only exists on newer systems:

Swift Runtime availability checks

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

On Linux the final * matches, so the first branch runs and the program prints new enough for the new API. Do not confuse the two systems: #if compiler/#if swift decide at compile time which code exists, while #available decides at run time which OS features you can call.

How Swift evolves: the proposal process

Swift is open source, and its changes follow a public process:

  1. Pitch. Someone describes an idea on the Swift Forums to collect feedback.
  2. Proposal. The idea becomes a written proposal numbered SE-NNNN in the swift-evolution repository on GitHub, with motivation, the detailed design, source compatibility effects and alternatives.
  3. Review. The Language Steering Group schedules a review period, usually one to two weeks, in which anyone can comment.
  4. Decision. The proposal is accepted, accepted with modifications, returned for revision, or rejected. Accepted proposals are implemented and land behind a feature flag first, then in a release.

A few well-known proposal numbers are worth remembering because you will see them in release notes and blog posts: SE-0296 (async/await), SE-0306 (actors), SE-0380 (if and switch expressions), SE-0390 (noncopyable types), SE-0393 (parameter packs) and SE-0413 (typed throws). Each proposal explains why a feature looks the way it does, so reading one is the fastest way to learn a feature in depth. The README of the evolution repository also keeps a status page listing every proposal and the version that shipped it.

Compatibility is a design constraint. The Swift team promises source compatibility within a language mode and works hard on ABI stability on Apple platforms, which is why changes that break code are put behind new language modes and why migration tooling exists.

Habits for living with a moving language

  • Pin your toolchain in CI (and test on at least the oldest and newest version you support). Tools such as swiftly or Docker images make switching easy.
  • Read the release notes of each new version once; they list deprecations that will become errors later.
  • Treat warnings as work items. Deprecated APIs and concurrency warnings are the compiler telling you what the next language mode will enforce.
  • Prefer standard-library solutions over old workarounds; many third-party helpers have been absorbed (Result, count(where:), regex, Duration).
  • Check the date of every answer you find online. A Stack Overflow answer from 2016 may use DispatchQueue.main.async and NSString bridging where modern code uses @MainActor and String.
  • Gate new syntax with #if compiler(>=...) when a package must support several toolchains, and remove the gate when you raise the minimum version.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What is the difference between the toolchain version and the language mode?

    A 6.3 compiler can compile a module in Swift 5 mode or Swift 6 mode. Upgrading the compiler does not change the language mode automatically.
  2. 2. What is the main change introduced by the Swift 6 language mode?

    Swift 6 mode enforces strict concurrency checking, turning many potential data races into compile-time errors.
  3. 3. Which approach fixes the error 'main actor-isolated var can not be mutated from a nonisolated context'?

    The error says the access is not on the actor that owns the variable. Putting the access on the main actor, or protecting the state with its own actor, makes it safe.
  4. 4. What does #if compiler(>=6.2) decide?

    #if compiler is conditional compilation. Code in a false branch is not type checked, so it can use syntax only a newer compiler understands.
  5. 5. What is an upcoming feature?

    Upcoming features let you adopt future defaults early with -enable-upcoming-feature or a SwiftPM setting, so the migration can happen one change at a time.

Summary

  • The toolchain version (6.3) and the language mode (5 or 6) are separate; upgrading the compiler does not change the mode.
  • Swift 6 mode makes data-race safety a compile-time guarantee: globals, shared classes and captures must be isolated, protected by an actor or Sendable.
  • The releases from 5.0 to 6.3 added opaque types, property wrappers, concurrency, regex, macros, if/switch expressions, parameter packs, noncopyable types, typed throws, Int128, InlineArray and Span.
  • #if compiler(>=...), #if swift(>=...) and #if hasFeature(...) select code at compile time; #available checks the OS at run time.
  • Upcoming features are opt-in flags for future defaults; experimental features are unfinished and may change.
  • Migrate gradually: new toolchain first, strict-concurrency warnings next, then the Swift 6 mode per module.
  • Swift evolves in the open through pitches, numbered SE proposals, reviews and decisions; reading proposals is the best way to understand a feature.

Next: Performance Tips