Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Understanding Task{ } behaviour in iOS Swift Concurrency

func someTask() {
    let _=""
    Task{
        let _=""
        let data=await doBackgroundTask()
        let _=data // Update UI with data
    }
}

func doBackgroundTask() async->String{
    // Heavy work here
    return ""
} 

Steps

  1. someTask() is invoked from SwiftUI Button click
  2. Check this screenshot Code screenshot

3. I have added breakpoint at line no 15, 17, 19, 25

  • a) line no 15, 17, 19 are invoking in main thread, which is good and as expected
  • b) But line no 25 is also invoking in main thread, which is not expected and I want it to be in background thread.

What am I missing ?

like image 474
VIJAY SACHAN Avatar asked Oct 19 '25 19:10

VIJAY SACHAN


1 Answers

Assuming you wrote this in a View struct, doBackgroundTask is actually implicitly main actor-isolated, because the View protocol is declared to be main actor-isolated.

You should add nonisolated if you don't want it to be actor-isolated.

nonisolated func doBackgroundTask() async -> String { ... }
like image 62
Sweeper Avatar answered Oct 22 '25 13:10

Sweeper



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!