Avatar
Avatar
omochimetaru
@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 { do { return try withoutActuallyEscaping(operation) { operation throws -> Result in var op: () throws -> Result = operation for (taskLocal, valueDuringOperation) in repeat each taskLocalValuesDuringOperation { op = { [op] () throws -> Result in return try taskLocal.withValue(valueDuringOperation, operation: op, file: file, line: line) } } return try operation() } } catch { throw error as! Failure } } withTaskLocalValues( (GlobalValues.$property1, 2), (GlobalValues.$property2, "World"), (GlobalValues.$property3, 4), ) { print(GlobalValues.property1, GlobalValues.property2, "\(GlobalValues.property3, default: "nil")") }
1 Hello nil