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)
}
SPONSORED Still waiting on your CI build? Speed it up ~3x with Blaze - change one line, pay less, keep your existing GitHub workflows. First 25 HWS readers to use code HACKING at checkout get 50% off the first year. Try it now for free!
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.