Why is private global not concurrency-safe?

Given this

// uniqueId.swift

private var v: Int = 0

@MainActor
func uniqueId () -> Int {
    defer {v += 1}
    return v
}

Why the error?

var 'v' is not concurrency-safe because it is nonisolated global shared mutable state

var v is private, it is used only inside the main-actor isolated func uniqueId, and therefore it is inherently concurrency-safe. no?

1 Like

There is no special exception for a file with a single function bound to a global actor. You just need to annotate the variable with @MainActor.

But you're right that it's impossible to have a race in this case. At least until you add more functions (or closures).

3 Likes