<!--
{
  "availability" : [
    "iOS: 8.0.0 -",
    "iPadOS: 8.0.0 -",
    "macCatalyst: 13.0.0 -",
    "macOS: 10.10.0 -",
    "tvOS: 9.0.0 -",
    "visionOS: 1.0.0 -",
    "watchOS: 2.0.0 -"
  ],
  "documentType" : "symbol",
  "framework" : "Swift",
  "identifier" : "/documentation/Swift/withExtendedLifetime(_:_:)-4mmpv",
  "metadataVersion" : "0.1.0",
  "role" : "Function",
  "symbol" : {
    "kind" : "Function",
    "modules" : [
      "Swift"
    ],
    "preciseIdentifier" : "s:s20withExtendedLifetimeyq0_x_q0_yq_YKXEtq_YKs5ErrorR_Ri_zRi0_zRi_0_r1_lF"
  },
  "title" : "withExtendedLifetime(_:_:)"
}
-->

# withExtendedLifetime(_:_:)

Evaluates a closure while ensuring that the given instance is not destroyed
before the closure returns.

```
func withExtendedLifetime<T, E, Result>(_ x: borrowing T, _ body: () throws(E) -> Result) throws(E) -> Result where E : Error, T : ~Copyable, T : ~Escapable, Result : ~Copyable
```

## Parameters

`x`

An instance to preserve until the execution of `body` is completed.

`body`

A closure to execute that depends on the lifetime of `x` being
extended. If `body` has a return value, that value is also used as the
return value for the `withExtendedLifetime(_:_:)` method.

## Return Value

The return value, if any, of the `body` closure parameter.

---

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)