Spot the bug
value(for:) always returns nil. Tap the line that causes it.
final class Store: @unchecked Sendable {private var values: [String: Int] = [:]private let queue = DispatchQueue(label: "store", attributes: .concurrent)func value(for key: String) -> Int? {var result: Int?queue.async { result = self.values[key] }return result}func set(_ value: Int, for key: String) {queue.async(flags: .barrier) { self.values[key] = value }}}
Hint 1 of 2
Does async wait for the closure?
Hint 2 of 2
Which line produces the return value?
Choose an answer, then open Show answer below to check it.
Show answer
- Answer: line 7
queue.async { result = self.values[key] }
Line 7 reads with async, so the function returns before the closure runs; result is still nil. Reads use queue.sync { values[key] }. The Swift 6 compiler also warns about mutating a captured var in concurrently-executing code.