A bug? Can't defer actor-isolated variable access

Hey, I'm seeing this issue using the compiler in Xcode Version 13.0 beta 3 (13A5192j)

class ViewController: UIViewController {
    var value : String? = "Hello"
    @IBAction func showAlert(_ sender: Any) {
        Task {
            defer { value = nil } // ← Property 'value' isolated to global actor 'MainActor' can not be mutated from this context
            // ~~await Task.sleep(1)~~ This doesn't even matter, but the await is why I'm using Task
        }
    }
}

This shouldn't be a problem, right? ViewController inherits from @MainActor UIViewController so all its properties and methods and spawned tasks should also be known to execute under the aegis of the main actor.

The async/await proposal says "A potential suspension point must not occur within a defer block." but that's not the case here since it is running on the same actor, right?

For a bit of context, I am actually awaiting on a withCheckedThrowingContinuation in order to display a file picker, and the API of the file picker doesn't allow for the continuation to be kept local to the withContinuation block. So it has to be saved as a member variable. And I reset that member to nil to indicated that the file picker is done and allow another file picker to be shown; if they try to show a picker and it isn't nil, that's an error. And I want to use defer because if the user cancel, I call the continuation to throw an error and I want the continuation member variable to be set to nil on both the happy and cancellation path.

(moved to compiler forum, from standard library forum)

This question appears to be about using Swift, not about developing the compiler itself; I've moved it to the Using Swift forum. Thanks!

1 Like

There's a bug where we aren't recognizing defer as part of its enclosing context; it should be fixed in a later beta.

2 Likes

This hasn't been fixed in the Xcode 13 release version. Whether or not the fix will be in some upcoming point release of Xcode, is it fixed in the separate Swift compiler?

Terms of Service

Privacy Policy

Cookie Policy