Skip to content

Commit c667b95

Browse files
hborlashahmishal
authored andcommitted
Fill in the approachable concurrency code example.
1 parent 6bb8667 commit c667b95

File tree

1 file changed

+28
-2
lines changed

1 file changed

+28
-2
lines changed

_posts/2025-NN-NN-swift-6.2-released.md

Lines changed: 28 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -20,8 +20,34 @@ Swift 6.2 lowers the barrier to concurrent programming with a set of changes des
2020
* **Intuitive `async` functions:** Write async code without concurrent access to mutable state. Previously, `nonisolated async` methods always switched to the global executor that manages the concurrent thread pool, which made it difficult to write async methods for class types without data-race safety errors. In Swift 6.2, you can migrate to an [upcoming feature](https://docs.swift.org/compiler/documentation/diagnostics/nonisolated-nonsending-by-default/) where `async` functions run in the caller’s execution context, even when called on the main actor.
2121
* **Opting into concurrency with `@concurrent`:** Introduce code that runs concurrently using the new `@concurrent` attribute. This makes it clear when you want code to remain serialized on actor, and when code may run in parallel.
2222

23-
```
24-
TODO: code example
23+
```swift
24+
// In '-default-isolation MainActor' mode
25+
26+
struct Image {
27+
// The image cache is safe because it's protected
28+
// by the main actor.
29+
static var cachedImage: [URL: Image] = [:]
30+
31+
static func create(from url: URL) async throws -> Image {
32+
if let image = cachedImage[url] {
33+
return image
34+
}
35+
36+
let image = try await fetchImage(at: url)
37+
38+
cachedImage[url] = image
39+
return image
40+
}
41+
42+
// Fetch the data from the given URL and decode it.
43+
// This is performed on the concurrent thread pool to
44+
// keep the main actor free while decoding large images.
45+
@concurrent
46+
static func fetchImage(at url: URL) async throws -> Image {
47+
let (data, _) = try await URLSession.shared.data(from: url)
48+
return await decode(data: data)
49+
}
50+
}
2551
```
2652

2753
Together, these improvements let you write data-race free code with less annotation overhead, provide more predictable behavior for async code, while still allowing you to introduce concurrency when you need it.

0 commit comments

Comments
 (0)