Detached Task

Hi
My First question here.
I need further clarity on using detached Task. I need to process data that could be quite time consuming and I dont want to do it on the main thread. I see a lot of post suggesting that one should keep away from detached tasks, but if you dont want to occupy the main thread I dont see an alternative. So here is a simplified version of my code.
Is this safe? It does not produce any warnings:

struct Detach{
    var test = 0
    
    //: –—–—–—–—–—–—–—–—–—–—–—–—–—–—–—–—–—–—–—–—–—–—–—–—–—–—–—–—–—–—–—–—–—–—–—–—–—–—–—–— ://
    mutating func testing()async{
            let detached = Task.detached(priority: .background) {
                // could be a very long processing algorithm
                return 50
            }
            test = await detached.value
    }

}

thanks

testing will already not run on the main thread, because in Swift 6/6.1 async functions that are not @MainActor never run on the main thread (note: @MainActor-ness can be inherited. If you are on a @MainActor type like a View, add nonisolated to remove the @MainActor-ness). You don't need to make a Task at all.

If and when you switch to Swift 6.2 mode, the migrator should put @concurrent on testing, which will keep it behaving the way it does in 6.0/6.1.

6 Likes