Avatar
treastrain / Tanaka.R 10/19/2025 8:23 PM
@swift-6.2.1 import Foundation struct GlobalValues { @TaskLocal static var property1 = 1 @TaskLocal static var property2: String = "Hello" @TaskLocal static var property3: Int? = nil var number = 1 } @inlinable @discardableResult public func withTaskLocalValues<each Value, Result, Failure>( _ taskLocalValuesDuringOperation: repeat (TaskLocal<each Value>, each Value), operation: () throws(Failure) -> Result, file: String = #fileID, line: UInt = #line ) throws(Failure) -> Result { try withoutActuallyEscaping(operation) { operation throws(Failure) -> Result in var operation = operation for (taskLocal, valueDuringOperation) in repeat each taskLocalValuesDuringOperation { operation = { [operation] () throws(Failure) -> Result in do { return try taskLocal.withValue(valueDuringOperation, operation: operation, file: file, line: line) } catch { throw error as! Failure } } } return try operation() } } withTaskLocalValues( (GlobalValues.$property1, 2), (GlobalValues.$property2, "World"), (GlobalValues.$property3, 4), ) { print(GlobalValues.property1, GlobalValues.property2, "\(GlobalValues.property3, default: "nil")") }