Pick the fix
Swift 6 rejects Task.detached { cache.store[url] = data } because ImageCache isn't Sendable. The cache is shared app-wide. Best fix?
final class ImageCache {
var store: [URL: Data] = [:]
}
let cache = ImageCache()
Task.detached { cache.store[url] = data }Hint 1 of 2
Is the state shared and mutable?
Hint 2 of 2
Which options only silence the compiler?
Choose an answer, then open Show answer below to check it.
Show answer
Answer: A Make ImageCache an actor and await cache.insert(data, for: url)
Correct. Shared mutable state belongs in an actor, which makes access safe.
Why not the others?
- B Mark the class
@unchecked Sendable. It compiles, but nothing protectsstore; two tasks writing at once is still a data race. - C Change
ImageCacheto a struct. Each task would get its own copy, so it is no longer a shared cache, and you can't mutate a capturedlet. - D Declare
nonisolated(unsafe) let cache. This opts out of checking for that variable; the race remains.