# Why Does the Compiler Allow Static Properties in Actors Without await?

**URL:** <https://forums.swift.org/t/why-does-the-compiler-allow-static-properties-in-actors-without-await/76973>\
**Category:** Using Swift\
**Tags:** concurrency, actors\
**Created:** [January 3, 2025, 5:15pm UTC](https://forums.swift.org/t/why-does-the-compiler-allow-static-properties-in-actors-without-await/76973 "2025-01-03T17:15:34Z")\
**Posts on this page:** 8\
**Page:** 1

<div class="post-metadata">

**Author:** ![nashysolutions](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/nashysolutions/32/15433_2.png) [@nashysolutions](https://forums.swift.org/u/nashysolutions)\
**Post date:** [January 3, 2025, 5:15pm UTC](https://forums.swift.org/t/why-does-the-compiler-allow-static-properties-in-actors-without-await/76973/1 "2025-01-03T17:15:34Z")

</div>

Hi everyone,

I’ve been working on a testing setup where I encountered some compiler behaviour that has me puzzled. Specifically, it relates to how async/await interacts with static properties in actors. I’m hoping to get a deeper understanding of why this behaviour is considered valid.

Here’s the relevant snippet:

```swift
// ensures tests are executed serially, protecting the shared static var
@globalActor
actor TestActor {
    static let shared = TestActor()
}

@TestActor
@Suite("KeychainKeys Tests") struct KeychainKeysTests {
    
    // making this an actor to keep the compiler happy, even though this
// will only be used within the TestActor...
    actor MockBundle: XcodeBundle {
        static var identifier = ""
        
        static func extractIdentifier() throws -> String {
            return identifier
        }
    }

    @Test("Valid Bundle Identifier")
    func testEncryptionKeyWithValidIdentifier() {
        /// Given
// are we not crossing an actor boundary here? MockBundle actor <> TestActor
        MockBundle.identifier = "com.example.app"

        /// When
        let key = KeychainKeys<MockBundle>.encryptionKey

        /// Then
        let expectedHash = SHA256.hash(data: Data("com.example.app".utf8))
            .map { String(format: "%02x", $0) }.joined()
        #expect(key == expectedHash, "Encryption key should match the expected hash.")
    }
}

```

**My Question**

In the above example:

• MockBundle is an actor.

• identifier is declared as a static var in the actor.

My understanding (correct me if I'm wrong here):

1. **Static properties are not actor-isolated:** This means they’re not protected by the actor’s isolation model.
2. **Static mutable state is inherently global mutable state:** The compiler treats MockBundle.identifier as potentially unsafe in concurrent contexts, which is why it enforces concurrency safety checks (e.g., requiring MockBundle to be an actor).

This feels like a **“maybe-safe” scenario** , where the compiler is satisfied as long as the actor declaration is present, but it doesn’t guarantee thread safety for the static var.

**What I’d Like to Understand**

• **Why does the compiler enforce that** MockBundle **must be an actor to handle a** static var\*\*, but then allow direct access to that\*\* static var **without** await\*\*?\*\*

• **Is this a deliberate design choice, or is there room for improvement in how Swift enforces safety in this situation?**

• **Should static properties in actors behave differently to align more strictly with the actor isolation model?**

I appreciate that the actor model and async/await have strict rules for enforcing concurrency safety, but this particular case feels like a grey area to me. If anyone could clarify the reasoning behind this behaviour, I’d be very grateful!

Thank you in advance for your insights.

---

<div class="post-metadata">

**Author:** ![jamieQ](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/jamieq/32/5117_2.png) [@jamieQ](https://forums.swift.org/u/jamieQ)\
**Post date:** [January 3, 2025, 6:39pm UTC](https://forums.swift.org/t/why-does-the-compiler-allow-static-properties-in-actors-without-await/76973/2 "2025-01-03T18:39:52Z")

</div>

i'm fairly sure this is a bug. the example you have can be reduced to something like:

```swift
@main
struct S {

    actor A {
        static var mutableStatic = ["1"]
    }

    static func main() async {
        print("start")
        do {
            async let _ = {
                for _ in 1...100 {
                    A.mutableStatic.append("2")
                }
            }()
            async let _ = {
                for _ in 1...100 {
                    A.mutableStatic.append("3")
                }
            }()
        }
        print("done")
    }
}

```

and if you run this after having built it with thread sanitizer enabled\[1\], you'll get a runtime data race safety violation diagnostic.

changing from an `actor` to a `class`, marking the variable with a global actor annotation (or trying to explicitly mark it `nonisolated`), or moving the variable to be a mutable global all produce the expected compiler diagnostics about potentially unsafe concurrent access.

i encourage you to [file a bug](https://github.com/swiftlang/swift/issues/new/choose) if & when you have a chance.

* * *

1. `swiftc <example>.swift -sanitize=thread -parse-as-library -swift-version 6`

---

<div class="post-metadata">

**Author:** ![JuneBash](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/junebash/32/19323_2.png) [@JuneBash](https://forums.swift.org/u/JuneBash)\
**Post date:** [January 3, 2025, 6:56pm UTC](https://forums.swift.org/t/why-does-the-compiler-allow-static-properties-in-actors-without-await/76973/3 "2025-01-03T18:56:16Z")

</div>

With the caveat that I am not _certain_ about any of these answers...

> **Why does the compiler enforce that** MockBundle **must be an actor to handle a** static var\*\*, but then allow direct access to that\*\* static var **without** await\*\*?\*\*

Does the `XcodeBundle` protocol require it to be an actor? If not, then can you change it to `static let`? Does it need to be mutable?

There is also an implicit question here of "Why does the compiler allow the static var to be mutable"; I believe it may inherit the actor isolation of `@TestActor` from `KeychainKeysTests`, but I'm not sure.

> • **Is this a deliberate design choice, or is there room for improvement in how Swift enforces safety in this situation?**  
> • **Should static properties in actors behave differently to align more strictly with the actor isolation model?**

My understanding is that actor _instances_ protect mutable state. e.g., In order for static vars to be protected actor state, we would need to spin up an arbitrary instance of an actor, which may not always be statically possible.

Consider this example from [the actors language proposal](https://github.com/swiftlang/swift-evolution/blob/main/proposals/0306-actors.md#references-and-actor-isolation):

```swift
actor MyActor {
  let name: String
  var counter: Int = 0
  func f()
}

extension MyActor {
  func g(other: MyActor) async {
    print(name) // okay, name is non-isolated
    print(other.name) // okay, name is non-isolated
    print(counter) // okay, g() is isolated to MyActor
    print(other.counter) // error: g() is isolated to "self", not "other"
    f() // okay, g() is isolated to MyActor
    await other.f() // okay, other is not isolated to "self" but asynchronous access is permitted
  }
}

```

An actor can access its own state synchronously, but cannot access another actor's state synchronously, as each actor instance has its own 'async boundary'.

Hope that helps!

---

<div class="post-metadata">

**Author:** ![mattie](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/mattie/32/13267_2.png) [@mattie](https://forums.swift.org/u/mattie)\
**Post date:** [January 3, 2025, 8:49pm UTC](https://forums.swift.org/t/why-does-the-compiler-allow-static-properties-in-actors-without-await/76973/4 "2025-01-03T20:49:56Z")

</div>

Great guesses here, but we can test this by cutting inference short.

```swift
@globalActor
actor TestActor {
    static let shared = TestActor()
}

@TestActor
struct MyStruct {
    actor MyActor {
        static var identifier = ""
    }
    
    nonisolated func a() {
        print(MyActor.identifier)
    }
}

```

This compiles error-free. I'm pretty sure this is indeed a bug with static properties of actors. It actually shouldn't matter at the points of access anyways - the problem is at the definition within `MyActor`.

(I tried with the 6.1 snapshot too just for kicks, and also does not produce an error)

In fact, we can get even simpler. I see now way this code could be safe, but it compiles.

```swift
actor MyActor {
    static var identifier = ""
}

nonisolated func a() {
    print(MyActor.identifier)
}

```

---

<div class="post-metadata">

**Author:** ![allevato](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/allevato/32/385_2.png) [@allevato](https://forums.swift.org/u/allevato)\
**Post date:** [January 3, 2025, 8:57pm UTC](https://forums.swift.org/t/why-does-the-compiler-allow-static-properties-in-actors-without-await/76973/5 "2025-01-03T20:57:08Z")

</div>

Static properties/methods of actors are no different than static properties/methods of other types; as @JuneBash mentioned above, actor isolation is based around having some _instance_ of the actor. From [SE-0306](https://github.com/swiftlang/swift-evolution/blob/main/proposals/0306-actors.md):

> By default, the instance methods, properties, and subscripts of an actor have an isolated `self` parameter. This is true even for methods added retroactively on an actor via an extension, like any other Swift type. Static methods, properties, and subscripts do not have a `self` parameter that is an instance of the actor, so they are not actor-isolated.

So they don't get any isolation from being declared on the actor, but if they aren't being diagnosed when they're potentially being mutated concurrently, that may be a bug.

---

<div class="post-metadata">

**Author:** ![JuneBash](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/junebash/32/19323_2.png) [@JuneBash](https://forums.swift.org/u/JuneBash)\
**Post date:** [January 3, 2025, 8:59pm UTC](https://forums.swift.org/t/why-does-the-compiler-allow-static-properties-in-actors-without-await/76973/6 "2025-01-03T20:59:07Z")

</div>

Yeah, you're right; this does seem to be an unsafe bug. Running this code in a fresh executable package...

```swift
actor MyActor {
    static var value = 0
}

nonisolated func a() async {
  await withTaskGroup(of: Void.self) { taskGroup in
    for _ in 0..<1000 {
      taskGroup.addTask {
        MyActor.value += 1
      }
    }
  }
  print(MyActor.value)
}

```

...compiles and runs without warnings, but does not deterministically print `1000` like one would expect. This seems to me like unsafe, undefined behavior and a bug.

---

<div class="post-metadata">

**Author:** ![allevato](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/allevato/32/385_2.png) [@allevato](https://forums.swift.org/u/allevato)\
**Post date:** [January 3, 2025, 9:20pm UTC](https://forums.swift.org/t/why-does-the-compiler-allow-static-properties-in-actors-without-await/76973/7 "2025-01-03T21:20:22Z")

</div>

> [@JuneBash](#):
>
> ...compiles and runs without warnings, but does not deterministically print `1000` like one would expect. This seems to me like unsafe, undefined behavior and a bug.

And to add to this, all it takes is changing `actor MyActor` to `class MyActor` to get the compiler to diagnose it (with `-swift-version 6`). Since static data is really just global data, it should be diagnosed the same way whether it's on an `actor` or some other type.

---

<div class="post-metadata">

**Author:** ![nashysolutions](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/nashysolutions/32/15433_2.png) [@nashysolutions](https://forums.swift.org/u/nashysolutions)\
**Post date:** [January 4, 2025, 7:24am UTC](https://forums.swift.org/t/why-does-the-compiler-allow-static-properties-in-actors-without-await/76973/8 "2025-01-04T07:24:44Z")

</div>

Thank you all.  
I have raised this as a `suggested improvement` instead of a bug.

> <https://github.com/swiftlang/swift/issues/78435>
>
> \### Motivation
> 
> Currently, when a static property is declared in an actor and ac…cessed concurrently from multiple tasks, the Swift compiler does not provide any warnings or errors about potential race conditions. This lack of diagnostics can lead to subtle and hard-to-diagnose bugs, especially for developers who assume that all properties within an actor are isolated, including static ones.
> 
> In contrast, when a class is used instead of an actor, the compiler correctly identifies and prevents race conditions caused by concurrent access. This inconsistent behaviour between actors and classes can create confusion and lead to incorrect assumptions about the safety of static properties in actors.
> 
> \### Proposed solution
> 
> Introduce compiler diagnostics for concurrent access to static properties in actors. Specifically:
> 1.	Warn developers when a static property in an actor is accessed in a concurrent context.
> 2.	Provide clear messaging that static properties are not actor-isolated and must be explicitly synchronised if accessed concurrently.
> 3.	Optionally, recommend alternative approaches.
> 
> \`\`\`swift
> actor MyActor {
> static var value = 0
> }
> 
> nonisolated func a() async {
> await withTaskGroup(of: Void.self) { taskGroup in
> for \_ in 0..\<1000 {
> taskGroup.addTask {
> MyActor.value += 1 // This should trigger a compiler warning about potential race conditions.
> }
> }
> }
> print(MyActor.value)
> }
> \`\`\`
> 
> Expected Diagnostic:
> \_Concurrent access to static property 'value' in actor 'MyActor' is not safe and may result in a race condition.\_
> 
> \### Alternatives considered
> 
> 1.	Status Quo: Continue without compiler diagnostics. This approach leaves developers vulnerable to race conditions when using static properties in actors without realising the lack of isolation.
> 2.	Documentation Update: Update the Swift documentation to clarify that static properties in actors are not isolated. While this would improve awareness, it relies on developers reading the documentation and may not be as effective as compiler diagnostics.
> 3.	Enhanced Actor Model: Extend the actor isolation model to include static properties. However, this would likely introduce significant complexity and break existing code, making it a less feasible option.
> 
> \### Additional information
> 
> This feature would align with Swift’s focus on safety and concurrency. By making such race conditions explicit at compile time, it would prevent subtle bugs and reduce confusion for developers adopting the actor model.
> 
> This issue was discovered by the developers in this thread: https://forums.swift.org/t/why-does-the-compiler-allow-static-properties-in-actors-without-await/76973
