Global actor isolation and local variables / functions, bugs or by design?

Are those bugs or designed behaviors?

@MainActor
class Object {
  @MainActor // can be implicit
  var num = 0
}

@MainActor
struct Foo {
  @MainActor // can be implicit
  let object = Object()

  @MainActor // can be implicit
  func foo() {

    func bar_1() -> Int {
      // ERROR: Property 'num' isolated to global actor 'MainActor' can not be
      // referenced from this synchronous context
      object.num
    }

    @MainActor // workaround
    func bar_2() -> Int {
      object.num // okay
    }

    var num_1: Int {
      get {
        // ERROR: Property 'num' isolated to global actor 'MainActor' can not be
        // referenced from this synchronous context
        object.num
      }
    }

    var num_2: Int {
      get async {
        // ERROR: Expression is 'async' but is not marked with 'await'
        /* await */ object.num
      }
    }

    // Basically fixed `num_2`.
    // This one is trivial, but not what I actually need.
    var num_3: Int {
      get async {
        await object.num
      }
    }

    // ERROR: Local variable 'num_4' cannot have a global actor
    @MainActor
    var num_4: Int {
      get async {
        await object.num
      }
    }
  }
}

The global actors proposal says in it's detailed design that "Local variables and constants cannot be marked with a global actor attribute", but why? If they cannot be marked, then they do or don't inherit the actor's protective isolation?

  • Why does bar_2 work and bar_1 doesn't?
  • Why is num_1 not allowed?

This was tested with Xcode Beta 4.


cc @Douglas_Gregor, @John_McCall

Terms of Service

Privacy Policy

Cookie Policy