skip to content

In Swift, a temporary-file wrapper deletes its file in deinit, yet the file vanishes before the code that reads it; why, and how do you pin its lifetime?

level: seniorimportance: should knowfreq 25%

answer

  1. last use, not the closing brace
  2. an object nobody named
  3. what counts as a deinit barrier
  4. a fence for a lifetime

basics

~20 s

Swift guarantees an object only until its last use, not until the closing brace; a wrapper used as a temporary, as in TempFile(...).url, is freed when that statement ends. Name it and pin it with withExtendedLifetime, or extendLifetime in a defer (Swift 6.2).

solid answer

~50 s

ARC promises to keep an instance alive through its last use, not to the end of the enclosing scope. The everyday trap is a temporary: in `let url = try TempFile(contents: csv).url` nothing holds the wrapper after that statement, so its `deinit` deletes the file before the next line reads it — in debug and optimized builds alike. A named local is safer but still not scoped: since Swift 5.7 the optimizer may release it after its last use, though it won't move that release across a deinit barrier (a synchronization point such as a system call, a weak or unowned load, or a pointer access). When correctness depends on the object outliving a use that does not go through it, say so in code: `withExtendedLifetime(file) { … }`, or `defer { extendLifetime(file) }` in Swift 6.2 and later. Better still, make the read go through the wrapper.

code

swift · 32 lines
swift
import Foundation

final class TempFile {
    let url: URL
    init(contents: String) throws {
        url = FileManager.default.temporaryDirectory
            .appendingPathComponent(UUID().uuidString)
        try contents.write(to: url, atomically: true, encoding: .utf8)
    }
    deinit { try? FileManager.default.removeItem(at: url) }
}

func broken() throws -> String {
    let url = try TempFile(contents: "id,total").url    // the instance is a temporary
    return try String(contentsOf: url, encoding: .utf8)  // the file is already gone
}

func pinned() throws -> String {
    let file = try TempFile(contents: "id,total")
    defer { extendLifetime(file) }                       // Swift 6.2 and later
    return try String(contentsOf: file.url, encoding: .utf8)
}

func pinnedWithClosure() throws -> String {
    let file = try TempFile(contents: "id,total")
    return try withExtendedLifetime(file) {
        try String(contentsOf: file.url, encoding: .utf8)
    }
}

print((try? broken()) ?? "broken: read failed")
print(try pinned(), try pinnedWithClosure())

go deeper

for a junior

Recall that an object can be freed right after its last use, and that a temporary created inside an expression dies at the end of that statement.

for a middle

Explain why copying a URL or path out of a wrapper does not keep the wrapper alive, and how naming it and routing reads through it fixes that.

for a senior

Diagnose early deinit from a temporary or an unpinned local, know what deinit barriers protect since Swift 5.7, and pin with withExtendedLifetime or extendLifetime.

for a principal

Prefer types whose cleanup cannot race their users, such as reads that go through the owning object, over relying on call sites to remember a lifetime fence.

## What ARC actually promises Under **Automatic Reference Counting (ARC)** a class instance stays alive while a strong reference to it is in use. The promise is about **use**, not about **scope**: Swift may release a local reference after its last use instead of at the closing brace. The Swift 5.7 release notes describe this directly — new rules "to shorten the lifetime of variables when optimization is allowed", with the compiler tracking each variable's lexical scope so that "the most common programming patterns that depend on extended variable lifetimes are safe" without `withExtendedLifetime`. The word that matters is *most*. A `deinit` with an external side effect — deleting a file, closing a descriptor, unregistering a callback — turns the moment of release into observable behaviour, and that is where lifetime bugs appear. ## The temporary trap The most common way the file disappears early does not involve the optimizer at all: ```swift let csv = "id,total" let url = try TempFile(contents: csv).url // the instance is a temporary let text = try String(contentsOf: url, encoding: .utf8) ``` Nothing names the `TempFile` instance. Once the first statement has copied out `url`, no strong reference remains, the instance is released, and `deinit` deletes the file. Built with Swift 6.4, the read fails at both `-Onone` and `-O`. Holding the `URL` does not help: a `URL` is a value, not a reference to the wrapper. ## Named locals and deinit barriers Give the wrapper a name and the picture changes. Since Swift 5.7, a named local has a **lexical lifetime**: the optimizer may still shorten it, but it may not move the release across a **deinit barrier**. The compiler's ownership notes list three kinds: 1. synchronization points — locks, memory barriers, system calls; 2. loads of `weak` or `unowned` references; 3. accesses through pointers. A file read is a system call, so in practice the named wrapper survives it. But this is an optimizer rule designed to keep common code working, not a promise that the object lives to the end of its scope. | Situation | When the instance can be released | Safe for the file read? | |---|---|---| | used only as a temporary inside an expression | at the end of that statement, in any build | no | | named local, the read goes through the object (`file.read()`) | after that read | yes | | named local, the read uses a copied URL, path or descriptor | after the last use, but not across a deinit barrier | usually; state it explicitly | | the only reference is an `Unmanaged` value | whenever the owning references go | no | ## Pinning the lifetime When an object must outlive a use that does not go through it, say so in code: - **`withExtendedLifetime(_:_:)`** — "Evaluates a closure while ensuring that the given instance is not destroyed before the closure returns." It has an overload whose closure receives the instance, and both support typed throws, so `try withExtendedLifetime(file) { try String(contentsOf: file.url, encoding: .utf8) }` compiles as written. - **`extendLifetime(_:)`** — added in Swift 6.2 by SE-0465, it takes no closure. The proposal notes that the recommended style had become a `defer` with an empty closure, and replaces it with `defer { extendLifetime(file) }`. - **Route the use through the object.** A method such as `file.contents()` keeps the instance in use for exactly as long as it matters, and is clearer than any fence. Prefer the third in your own types; reach for the first two when the API you call takes a value copied out of the object. ## Order and timing of deinits The same use-based rule makes the **order** in which locals are destroyed an implementation detail. With two class-typed locals ending together, a Swift 6.4 debug build destroyed the later-declared one first, while an optimized build destroyed them in declaration order. If one cleanup must precede another, make it explicit: set optionals to `nil` in the order you need, or let one object own the other, since an owner's `deinit` runs before its stored properties are released. ## In review When a type's `deinit` has an external effect, check its call sites in this order: - **temporaries** — any expression that creates the object and immediately copies a value out of it; - **copied handles** — a URL, path, descriptor or pointer taken from the object and used after the object's last use; - **unowned hand-offs** — the object passed somewhere that does not retain it, such as a raw pointer. The fix is almost never to trust the scope; it is to keep a name and either route the use through the object or pin it.

  • Two class-typed locals go out of scope together; in which order do their deinits run?
    Don't rely on one. Compiled with Swift 6.4, the same snippet destroyed the later-declared local first in a debug build and the earlier-declared one first with `-O`. If one cleanup must precede the other, set optionals to `nil` in the order you need, or have one object own the other: an owner's `deinit` runs before its stored properties are released.
  • Does `isolated deinit` change when a main-actor class's deinit runs?
    A plain `deinit` in a `@MainActor` class is nonisolated and runs wherever the last release happens, so Swift 6.4 rejects calling a main-actor method from it: "call to main actor-isolated instance method 'flush()' in a synchronous nonisolated context". Swift 6.2's `isolated deinit` (SE-0371) runs it on the main actor, which, as the compiler's note says, "may be later than 'nonisolated deinit'".

  • A local always lives until the closing brace of its scope
  • Holding the wrapper's URL keeps the wrapper instance alive
  • If it works in a debug build, the lifetime is guaranteed
  • Locals are always destroyed in reverse declaration order
  • withExtendedLifetime copies the object to keep it alive

Assumes Swift 6.4: lexical-lifetime rules date from Swift 5.7, extendLifetime(_:) and isolated deinit arrived in Swift 6.2; withExtendedLifetime works on every supported release.