'@MainActor is not safely when it used with propertyWrapper?

Combined use @mainActor and propertyWrapper is not safe? The code will execute directly in the background thread. It is a bug?

Here is the demo:

struct DetailView: View {
    
    @MainActor
    @Environment(\.dismiss)
    private var dismiss
    
    var body: some View {
        Text("Hello")
            .task {
                await asyncWork()
            }
    }

    private func asyncWork() async {
        Thread.sleep(forTimeInterval: 1)

        // Crash. Because of not in main Thread.
        await dismiss()
    }

}


Solution 1:[1]

I found the answer. Swift concurrency will get dismiss in main queue. Then back to background execute the dismiss block.

It look like


@MainActor var dismiss: ()->(Void) {
  // get in main thread
  { ... }
}

func asyncWork() async {
  Thread.sleep(forTimeInterval: 1) // background thread
  let dismiss = self.dismiss // main thread
  dismiss() // background thread. 
}


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Chihi Lim