swiftswift-concurrency

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

What am I missing ?


Solution

  • 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 { ... }