Swift: Enums with stored properties not thread safe even when mutated using a serial queue

Viewed 128

This issue relates to another issue reported on the Apple Developer forum titled How to avoid Data Races in deinit from 4 years ago. I am seeing crashes in production related to associated data and outlined consume code added by the compiler to deinitialize enums with associated data that contain reference types.

When trying to find if someone else has faced the same issue, I stumbled across the above post. I reduced the example from that post to a simpler example below and reliably get a crash due to bad access. (I ran this in Playground and got the crash but no stack trace)

import Foundation
class Racer {
    let queue = DispatchQueue(label: "Racer-\(UUID())")
    var value: String? = "" // Desugars to Optional<String>, an enum
    func race() {
        queue.async {[weak self] in
            self?.value = UUID().uuidString
        }
    }
}
let racer = Racer()
while true {
    racer.race()
}

error: Execution was interrupted, reason: EXC_BAD_ACCESS (code=1, address=0x357d20cc94c0).

Is this a bug in Swift that has yet to be patched?

0 Answers
Related