SE-0302 adds support for “sendable” data, which is data that can safely be transferred to another thread. This is accomplished through a new Sendable
protocol, and an @Sendable
attribute for functions.
Many things are inherently safe to send across threads:
Bool
, Int
, String
, and similar.Array<String>
or Dictionary<Int, String>
.String.self
.These have been updated to conform to the Sendable
protocol.
As for custom types, it depends what you’re making:
Sendable
because they handle their synchronization internally.Sendable
if they contain only values that also conform to Sendable
, similar to how Codable
works.Sendable
as long as they either inherits from NSObject
or from nothing at all, all properties are constant and themselves conform to Sendable
, and they are marked as final
to stop further inheritance.Swift lets us use the @Sendable
attribute on functions or closure to mark them as working concurrently, and will enforce various rules to stop us shooting ourself in the foot. For example, the operation we pass into the Task
initializer is marked @Sendable
, which means this kind of code is allowed because the value captured by Task
is a constant:
func printScore() async {
let score = 1
Task { print(score) }
Task { print(score) }
}
However, that code would not be allowed if score
were a variable, because it could be accessed by one of the tasks while the other was changing its value.
You can mark your own functions and closures using @Sendable
, which will enforce similar rules around captured values:
import Foundation
func runLater(_ function: @escaping @Sendable () -> Void) -> Void {
DispatchQueue.global().asyncAfter(deadline: .now() + 3, execute: function)
}
GO FURTHER, FASTER Unleash your full potential as a Swift developer with the all-new Swift Career Accelerator: the most comprehensive, career-transforming learning resource ever created for iOS development. Whether you’re just starting out, looking to land your first job, or aiming to become a lead developer, this program offers everything you need to level up – from mastering Swift’s latest features to conquering interview questions and building robust portfolios.
Sponsor Hacking with Swift and reach the world's largest Swift community!
Download all Swift 5.5 changes as a playground Link to Swift 5.5 changes
Link copied to your pasteboard.