Swift Concurrency Riddle - TaskLocal

Swift Concurrency Riddle - TaskLocal

Intro If you’re able to solve this, it means you understand TaskLocal really well. Riddle Look at the attached code snippet and guess: What will be printed at each step? Is the order of prints always the same? class Riddler { @TaskLocal static var message = "Hello" static func riddleMe() { Self.$message .withValue("Bye", operation: { print("Print 1: \(Self.message)") // ??? Task { print("Print 2: \(Self.message)") // ??? } Task.detached { print("Print 3: \(Self.message)") // ??? } }) print("Print 4: \(Self.message)") // ??? } } Riddler.riddleMe() Hint Do you want to learn more about TaskLocal and Test Scoping in Swift 6.1 first? - Check out my blog post on “Concurrency-Safe Testing in Swift 6.1 with TaskLocal and Test Scoping” HERE. ...

May 17, 2025 · 2 min · Maciej Gomolka