Are top-level global variables still already implicitly isolated to @MainActor in Swift 6?

The documentation for Migrating to Swift 6 says go apply SE-0412.

To start, enable a single upcoming concurrency feature. This allows you to focus on one specific type of problem at a time.
...
SE-0412 Strict concurrency for global variables GlobalConcurrency
...

SE-0412

Proposed solution

Under strict concurrency checking, require every global variable to either be isolated to a global actor or be both:

  1. immutable
  2. of Sendable type

Global variables that are immutable and Sendable can be safely accessed from any context, and otherwise, isolation is required.

Top-level global variables are already implicitly isolated to @MainActor and therefore automatically meet these proposed requirements.

Am I reading the proposal incorrectly?

Because the following code won't compile, despite what the proposal says.

var counter: Int = 0

@main
enum A {
    static func main () async throws {
    }
}       
swiftc -parse-as-library -swift-version 6 -strict-concurrency=complete it.swift
it.swift:1:5: error: var 'counter' is not concurrency-safe because it is nonisolated global shared mutable state
1 | var counter: Int = 0
  |     |- error: var 'counter' is not concurrency-safe because it is nonisolated global shared mutable state
  |     |- note: convert 'counter' to a 'let' constant to make 'Sendable' shared state immutable
  |     |- note: annotate 'counter' with '@MainActor' if property should only be accessed from the main actor
  |     `- note: disable concurrency-safety checks if accesses are protected by an external synchronization mechanism
2 | 
3 | @main

I am very confused. :confused:

The proposal uses the term "top-level global" to mean a global variable in script mode, e.g. in a main.swift file that does not contain @main. Those global variables are implicitly isolated to @MainActor. That inference does not apply to other global variables. The concurrency model in top-level code is detailed in SE-0343: Concurrency in Top-level Code.

4 Likes

Thank you.