IdentifiableContinuation is a lightweight wrapper around CheckedContinuation
that conforms to Identifiable
and includes an easy to use cancellation handler with the id.
IdentifiableContinuation can be installed by using Swift Package Manager.
Note: IdentifiableContinuation requires Swift 5.10 on Xcode 15.4+. It runs on iOS 13+, tvOS 13+, macOS 10.15+, Linux and Windows.
To install using Swift Package Manager, add this to the dependencies:
section in your Package.swift file:
.package(url: "https://github.com/swhitty/IdentifiableContinuation.git", .upToNextMajor(from: "0.3.0"))
With Swift 6, usage is similar to existing continuations.
let val: String = await withIdentifiableContinuation {
continuations[$0.id] = $0
}
The body closure is executed syncronously within the current isolation allowing actors to mutate their isolated state.
An optional cancellation handler is called when the task is cancelled. The handler is @Sendable
and can be called at any time after the body has completed.
let val: String = await withIdentifiableContinuation {
continuations[$0.id] = $0
} onCancel: { id in
// @Sendable closure executed outside of actor isolation requires `await` to mutate actor state
Task { await self.cancelContinuation(with: id) }
}
The above is also compatible in Swift 5 language mode using a Swift 6 compiler e.g. Xcode 16
While behaviour is identical, Swift 5 compilers (Xcode 15) are unable to inherit actor isolation through the new #isolation
keyword (SE-420) so an isolated
reference to the current actor must always be passed.
let val: String = await withIdentifiableContinuation(isolation: self) {
continuations[$0.id] = $0
}
IdentifiableContinuation is primarily the work of Simon Whitty.