<!--
{
  "availability" : [
    "iOS: 13.0.0 -",
    "iPadOS: 13.0.0 -",
    "macCatalyst: 13.0.0 -",
    "macOS: 10.15.0 -",
    "tvOS: 13.0.0 -",
    "visionOS: 1.0.0 -",
    "watchOS: 6.0.0 -"
  ],
  "documentType" : "symbol",
  "framework" : "Swift",
  "identifier" : "/documentation/Swift/TaskLocal/withValue(_:operation:file:line:)-79atg",
  "metadataVersion" : "0.1.0",
  "role" : "Instance Method",
  "symbol" : {
    "kind" : "Instance Method",
    "modules" : [
      "Swift"
    ],
    "preciseIdentifier" : "s:12_Concurrency9TaskLocalC9withValue_9operation4file4lineqd__x_qd__yKXESSSutKlF"
  },
  "title" : "withValue(_:operation:file:line:)"
}
-->

# withValue(_:operation:file:line:)

Binds the task-local to the specific value for the duration of the
synchronous operation.

```
@discardableResult final func withValue<R>(_ valueDuringOperation: Value, operation: () throws -> R, file: String = #fileID, line: UInt = #line) rethrows -> R
```

## Discussion

The value is available throughout the execution of the operation closure,
including any `get` operations performed by child-tasks created during the
execution of the operation closure.

If the same task-local is bound multiple times, be it in the same task, or
in specific child tasks, the “more specific” binding is returned when the
value is read.

If the value is a reference type, it will be retained for the duration of
the operation closure.

If this method is called form a context where no current Swift concurrency task
is available, a fallback thread-local is used to manage the task locals and
all existing semantics of task-locals are upheld as-if a task was actually available.

---

Copyright &copy; 2026 Apple Inc. All rights reserved. | [Terms of Use](https://www.apple.com/legal/internet-services/terms/site.html) | [Privacy Policy](https://www.apple.com/privacy/privacy-policy)