[Swift 5.5] Can't get Task Local Value in async

tried to pass task Local Value for different task methods
I get the expected results for taskGroup, sub task and asyncDetached.
However, in async, I am not getting the task local value.
According to WWDC 2021, async should also inherit the task-local value from the origin.

Is there something wrong with the way I'm passing it?

Thanks for your help!

@main
class Main  {
    @TaskLocal
    static var taskName:TaskName?
    
    static func main() async {
        await $taskName.withValue(TaskName(name:"myTaskName")){
            
            printName("withValue") // myTaskName
            
            await withTaskGroup(of: Void.self){ group in
                printName("withTaskGroup") // myTaskName
                group.async {
                    printName("sub task") // myTaskName
                }
            }
            
            async{
                printName("async") // nil, but should be myTaskName
            }
            
            asyncDetached{
                printName("asyncDetached") // nil
            }
        }
    }

    
    static func printName(_ location:String = "") {
        print("\(location):",taskName?.name ?? "nil")
    }
}

class TaskName{
    var name:String = ""
    init(name:String){
        self.name = name
    }
}

result:

withValue: myTaskName
withTaskGroup: myTaskName
sub task: myTaskName
async: nil
asyncDetached: nil
Program ended with exit code: 0
1 Like

Thanks for reaching out!
Hm, we specifically have tests covering this.

I'll double check shortly; in the meantime you could try out the latest nightly snapshot toolchains from swift.org/downloads.

Thank you for your reply.
snapshot 2021-06-12 version is not working on my monterey + xcode 13. It holds LLDB error.
I will keep trying. But I found out that async has been changed to Task in the new version :)
Thanks again!

Thanks, I'll investigate this

Terms of Service

Privacy Policy

Cookie Policy