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

New Features in Swift Versions

New Features in Swift Versions

Since its release in 2014, Swift's appearance has changed several times.

The ++, C-style for, and println commonly seen in old tutorials fail to compile precisely because of version differences.

This article reviews key features by version, focusing on Swift 6's strict concurrency and migration path, and ends with a brief introduction to macros introduced in Swift 5.9.


Version timeline

First, an overview table aligning "what each version brought" along a timeline.

All features in the table can be found on the Swift Evolution proposal pages, which are marked "Implemented in Swift X".

Version Time Key characteristics
Swift 1.0 2014, with Xcode 6 First release, usable only on Apple platforms
Swift 2.0 2015, with Xcode 7 Error handling try / catch; open-sourced that December
Swift 3.0 2016, with Xcode 8 Major API naming changes, first parameter has no external label by default (SE-0046)
Swift 4.0 2017, with Xcode 9 Codable (SE-0166), exclusive memory access enforcement (SE-0176)
Swift 4.1 2018, with Xcode 9.3 Automatic synthesis of Equatable / Hashable (SE-0185)
Swift 4.2 2018, with Xcode 10 CaseIterable, #error / #warning, random number APIs
Swift 5.0 2019, with Xcode 10.2 ABI stability; Result (SE-0235), @unknown default (SE-0192), raw strings (SE-0200)
Swift 5.1 2019, with Xcode 11 Opaque return type some (SE-0244), property wrappers (SE-0258)
Swift 5.2 2020, with Xcode 11.4 Improved compiler diagnostics, faster builds
Swift 5.3 2020, with Xcode 12 Multiple trailing closures (SE-0279), @main (SE-0281)
Swift 5.4 2021, with Xcode 12.5 Result builders (SE-0289), the foundation of SwiftUI's declarative syntax
Swift 5.5 2021, with Xcode 13 async / await (SE-0296), actor (SE-0306), structured concurrency (SE-0304), Sendable (SE-0302)
Swift 5.6 2022, with Xcode 13.3 Existential type any (SE-0335)
Swift 5.7 2022, with Xcode 14 if let shorthand (SE-0345), primary associated types (SE-0346), incremental migration of concurrency checking (SE-0337)
Swift 5.8 2023, with Xcode 14.3 The mechanism for progressively enabling language features was further refined
Swift 5.9 2023, with Xcode 15 Macros (SE-0382, SE-0389, SE-0397), package access level (SE-0386), if / switch expressions (SE-0380), Observation (SE-0395)
Swift 5.10 2024, with Xcode 15.3 Complete concurrency checking
Swift 6.0 In 2024, with Xcode 16 Swift 6 language mode, data races escalated from warnings to errors; region isolation (SE-0414), global variable concurrency safety (SE-0412), typed throws (SE-0413)
Swift 6.x After 6.0 Continued refinement of concurrency diagnostics and toolchain on top of 6.0

Swift version evolution timeline: key features from 1.0 to 6.0, focusing on the two concurrency leaps of async/await in 5.5 and strict concurrency in 6.0

Note:Some minor items in the table have no specific version number because the official proposal pages do not state one explicitly Implemented in Swift X. When writing documentation, it is better to leave out an uncertain version number than to invent one.


A quick look at several high-frequency features

Below we pick a few groups of features that are most commonly used day to day and most likely to conflict with older tutorials, each with a runnable code sample.

some and any

some means "some specific conforming type, but I won't tell you which one"; the real type is determined at compile time.

any means "any type that conforms to this protocol", known only at runtime, at the cost of dynamic dispatch.

Example

import Foundation

protocol Greeter

{

    var name

:

String

{

get

}

    func greet

(

)

String

}

struct

RunoobGreeter

:

Greeter

{

    let name

:

String

    func greet

(

)

String

{

return

"Hello, (name)"

}

}

// some: returns a specific conforming type; the caller doesn't need to know which one

func makeGreeter

(

)

some Greeter

{

   

return

RunoobGreeter

(

name

:

"Runoob"

)

}

print

(

makeGreeter

(

)

.

greet

(

)

)

// any: put different conforming types into the same array, at the cost of dynamic dispatch

let greeters

:

[

any Greeter

]

=

[

    RunoobGreeter

(

name

:

"www.runoob.com"

)

,

    RunoobGreeter

(

name

:

"RUNOOB"

)

]

for

g in greeters

{

print

(

g.

greet

(

)

)

}



你好,Runoob

你好,www.runoob.com

你好,RUNOOB

For a fuller discussion of the trade-offs, see "Swift some and any》。

if let shorthand and if expressions

if let shorthand with the same name removes the repeated variable name; available since Swift 5.7 (SE-0345).

if / switch can be used directly as expressions to assign values to variables; available since Swift 5.9 (SE-0380).

Example

import Foundation

// if let shorthand with the same name

var site

:

String

?

=

"www.runoob.com"

if

let site

{

    print

(

"Site: (site)"

)

}

// if expression: assign directly to a let

let score

=

85

let level

=

if

score

=

90

{

"Excellent"

}

else

if

score

=

60

{

"Pass"

}

else

{

"Fail"

}

print

(

level

)

// Primary associated type: write some Collection as the return type, and the caller gets a concrete type

func makeScores

(

)

some Collection

<

Int

{

return

[

60

,

85

,

90

]

}

print

(

makeScores

(

)

.

count

)



站点:www.runoob.com

及格

3

async / await and actor

The concurrency model introduced in Swift 5.5 has three parts: async / await handles suspension and resumption, actor isolates mutable state, and Task and task groups handle structured concurrency.

Example

import Foundation

actor Counter

{

   

private

var value

=

0

    func increment

(

)

{

value

=

1

}

    func current

(

)

Int

{

value

}

}

func fetchTitle

(

_ id

:

Int

)

async

String

{

   

return

"Article (id)"

}

func run

(

)

async

{

   

// async let: launched concurrently, results collected together at await

    async let a

=

fetchTitle

(

1

)

    async let b

=

fetchTitle

(

2

)

    let titles

=

await

[

a, b

]

    print

(

titles

)

   

// TaskGroup: use when the number of tasks is dynamic

    let total

=

await withTaskGroup

(

of

:

Int.

self

)

{

group in

       

for

id in

1

...

3

{

            group.

addTask

{

await fetchTitle

(

id

)

.

count

}

       

}

        var sum

=

0

       

for

await n in group

{

sum

=

n

}

       

return

sum

   

}

    print

(

"Total characters: (total)"

)

   

// actor: internal state is accessed serially, so no data races occur

    let counter

=

Counter

(

)

    await withTaskGroup

(

of

:

Void.

self

)

{

group in

       

for

_ in

1

...

100

{

            group.

addTask

{

await counter.

increment

(

)

}

       

}

   

}

    print

(

"Count: (await counter.current())"

)

}

await run

(

)



["文章 1", "文章 2"]

字符总数:12

计数:100

For the full content of the concurrency chapter, see "Swift async and await" and "Swift Actors and Data Isolation》。


Swift 6 Strict Concurrency and Migration Recommendations

The biggest change in Swift 6 is not new syntax, but turning concurrency safety checks from "reminders" into "enforcement".

A data race occurs when two threads access the same memory at the same time, at least one of them is a write, and there is no synchronization.

Such bugs often do not reproduce in testing and only crash occasionally after release, so the compiler would rather stop you at compile time.

What Swift 6 language mode does

The Swift 6 compiler supports both Swift 5 and Swift 6 language modes, switched via -swift-version 5 or -swift-version 6.

In Swift 6 mode, concurrency issues that were only warnings become compile errors, and the build fails outright.

Check item Swift 5 mode Swift 6 mode
Passing non-Sendable values across isolation boundaries Warning Error
Global mutable state Warning Error (SE-0412)
actor-isolated properties accessed directly from outside Warning Error
Closures capturing non-Sendable values Warning Error

How Sendable works with actor

Sendable is a marker protocol meaning "values of this type can be safely passed across isolation domains".

For a value type whose stored properties are all Sendable, the compiler infers the conformance automatically; no need to write it by hand.

Example

import Foundation

// All stored properties of the struct are Sendable types, so the compiler infers Sendable automatically

struct

RunoobConfig

:

Sendable

{

    let timeout

:

Int

    let host

:

String

}

// A global let constant whose type is Sendable is safe under Swift 6 strict concurrency

let defaultConfig

=

RunoobConfig

(

timeout

:

30

, host

:

"www.runoob.com"

)

actor Store

{

   

private

var items

:

[

String

]

=

[

]

    func add

(

_ item

:

String

)

{

items.

append

(

item

)

}

    func all

(

)

[

String

]

{

items

}

}

func load

(

using

config

:

RunoobConfig

)

async

[

String

]

{

    let store

=

Store

(

)

    await store.

add

(

"(config.host):(config.timeout)"

)

   

return

await store.

all

(

)

}

let items

=

await load

(

using

:

defaultConfig

)

print

(

items

)

Run the code above in Swift 6 language mode, and the output is as follows.



$ swift -swift-version 6 RunoobConfig.swift

["www.runoob.com:30"]

What a typical error looks like

The following code runs in Swift 5 mode but fails to compile in Swift 6 mode because the global mutable state is not isolated.

Example

import Foundation

// A non-Sendable reference type

final

class

UnsafeBox

{

    var value

=

0

}

// Global mutable state: this is an error in Swift 6 language mode

var sharedBox

=

UnsafeBox

(

)

func bump

(

)

{

    sharedBox.

value

=

1

}

The first diagnostic the compiler gives is:



error: var 'sharedBox' is not concurrency-safe because it is nonisolated global shared mutable state [#MutableGlobalVariable]

Note:The code above is intentionally incomplete, just to show a real compile error; don't run it as-is. The correct approach for this kind of global mutable state is to put it inside an actor, or change it to let constants.

Three common fixes

The vast majority of errors fall into three paths: add isolation, add Sendable, or explicitly declare "I take responsibility".

The most recommended is adding isolation: mark UI state as @MainActor, and the compiler automatically guarantees it is only accessed on the main thread.

Example

import Foundation

// @MainActor: binds all members of the type to the main actor; this is how UI state should be written

@MainActor

final

class

RunoobViewModel

{

    var title

=

""

    func load

(

)

async

{

        title

=

"Swift Tutorial"

   

}

}

func run

(

)

async

{

    let vm

=

await RunoobViewModel

(

)

    await vm.

load

(

)

    print

(

await vm.

title

)

}

await run

(

)



Swift 教程

For legacy code that truly cannot be eliminated, you can use nonisolated(unsafe) to explicitly disable checking for a particular variable.

This keyword is like telling the compiler "I know it's unsafe, the responsibility is mine", so it must be accompanied by a comment explaining why.

Example

import Foundation

// nonisolated(unsafe): explicitly declares "I take responsibility here, don't check against isolation rules"

nonisolated

(

unsafe

)

var legacyCounter

=

0

func bump

(

)

{

    legacyCounter

=

1

}

bump

(

)

bump

(

)

print

(

legacyCounter

)



2

Steps to migrate from Swift 5 to Swift 6

Don't expect to clear all warnings in one shot; the official recommendation is to proceed in stages.

The key is to make problems visible first, then close them out module by module.

Step Approach Purpose
1 First upgrade to the latest toolchain, staying in Swift 5 language mode Rule out syntax-level interference
2 Turn on complete concurrency checking (-strict-concurrency=complete) Expose all data race issues as warnings
3 Enable Swift 6 language mode target by target Change only one module at a time to control the scope of impact
4 Add Sendable to data types passed across isolation boundaries Let the compiler confirm the data can safely cross threads
5 Mark UI and main-thread state as @MainActor Clarify isolation boundaries and reduce manual locking
6 Use @preconcurrency import to isolate dependencies not yet adapted Keep warnings from third-party modules from blocking migration
7 Only consider @unchecked Sendable or nonisolated(unsafe) last Keep escape hatches, but you must write a clear justification

Note:Swift 6 language mode is not mandatory; Swift 5 mode is still supported. But new projects are advised to enable Swift 6 directly—the later you migrate, the higher the cost.

For more detailed data race analysis and Sendable rules, see "Swift Sendable and Swift 6 Strict Concurrency》。


Introduction to macros (Swift 5.9)

Macros expand a small piece of code into another at compile time, with no extra runtime overhead.

They are fundamentally different from C macros: Swift macros are type-safe, and the implementation is itself an ordinary Swift program invoked by the compiler at compile time.

The macros introduced in Swift 5.9 fall into two categories, as shown in the table below.

Type Call form Typical use Proposal
Freestanding macros #macroName(...) Generate expressions or declarations, such as #Predicate SE-0382、SE-0397
Attached macros @macroName Add members or behavior to existing declarations, such as @Observable SE-0389

The most commonly used ready-made macro is @Observable provided by the Observation framework, which generates all the property observation code for you.

Example

import Foundation

import Observation

// @Observable is provided by the Observation framework and automatically generates observation code for properties

@Observable

final

class

RunoobModel

{

    var title

=

"Swift Tutorial"

    var viewCount

=

0

}

let model

=

RunoobModel

(

)

model.

viewCount

=

1

print

(

"(model.title) views: (model.viewCount)"

)



Swift 教程 阅读量:1

If you want to write your own macro, you need to create a SwiftPM package: put the declaration in a public-facing module and the implementation in a separate compile-time module.

The following is how the declaration part is written; it is a pure syntax snippet and needs a complete macro package to compile—it cannot be run on its own with the swift command.

Example

// Macro declaration: written in the publicly exposed module

@freestanding

(

expression

)

public

macro runoobURL

(

_ path

:

String

)

=

#externalMacro(

    module

:

"RunoobMacros"

,    

// The compile-time module where the implementation lives

    type

:

"RunoobURLMacro"

     

// The implementation type, responsible for generating code

)

// Use site: expands at compile time into a validated URL literal

let url

=

#runoobURL("https://www.runoob.com")

Note:Macro implementation code runs at compile time; it can read the source structure but cannot access runtime data. Before writing a custom macro, first check whether the standard library or system frameworks already provide one; the vast majority of scenarios don't need a custom implementation.


Common questions

The following questions are the ones most often asked during version upgrades.

Do I need to rewrite code when upgrading Swift versions?

Most versions are backward-compatible; breaking syntax changes were mainly concentrated in the Swift 2 to 3 transition.

The main migration cost of Swift 6 lies in concurrency checking, not syntax.

How do I confirm which version a feature became available in?

Check the corresponding Swift Evolution proposal page; the top of the page will say Implemented in Swift X.

You can also use #available to check the runtime OS version, but language features themselves are determined by the compiler version and cannot be checked at runtime.

Is Swift 6 language mode mandatory?

Not necessarily; Swift 5 language mode is still supported, and the two can be mixed target by target within the same project.

But everything strict concurrency checking catches is a real problem, so new projects are advised to enable it directly.

What's the difference between @Observable and the old ObservableObject?

@Observable is a macro; the compiler automatically generates observation code for each property, so properties no longer need to be marked @Published.

It tracks property access more finely, so only properties that are actually read trigger view updates.

Do macros slow down compilation?

A little, because the compiler needs to run the macro implementation code.

In return you get zero runtime overhead and a lower chance of errors than hand-written boilerplate.