skip to content

In Swift, how do a `consuming func close()` and `discard self` make a noncopyable database connection close exactly once, even when closing can fail?

level: seniorimportance: should knowfreq 20%

answer

  1. deinit cannot report failure
  2. a method that ends the value
  3. skip the destructor
  4. trivially destroyed stored properties
  5. self used after consume

basics

~20 s

Make close() a consuming method so the call ends the caller's binding; inside, close the handle, then discard self so deinit does not close it again. deinit stays as the fallback for connections nobody closed explicitly.

solid answer

~50 s

A `deinit` cannot throw, so a connection whose close can fail needs an explicit `consuming func close() throws`. Because the method consumes `self`, the caller's `db` is dead afterwards, and a second `close()` or a later query is rejected at compile time (`'db' consumed more than once`, `'db' used after consume`). A consuming method that simply returns destroys `self` and runs `deinit`, which would close the handle twice; `discard self` ends the value's lifetime without running `deinit`. Copy out the stored properties you need first, since touching `self` after `discard self` is `'self' used after consume`. In Swift 6.4 `discard self` is allowed only in a consuming method of a noncopyable type that has a `deinit`, inside that type's module, and only when every stored property is trivially destroyed, like an `Int32` handle. For a local, the `consume` operator does the same hand-off: `let worker = consume report`.

code

swift · 36 lines
swift
struct CloseError: Error { let status: Int32 }

func nativeClose(_ handle: Int32) -> Int32 { handle == 9 ? 5 : 0 }  // stand-in for a C call

struct DatabaseConnection: ~Copyable {
    private let handle: Int32
    init(handle: Int32) { self.handle = handle }

    func execute(_ sql: String) { print("[\(handle)] \(sql)") }

    consuming func close() throws {
        let handle = self.handle         // read what we need first
        let status = nativeClose(handle)
        discard self                     // end self's lifetime without running deinit
        if status != 0 { throw CloseError(status: status) }
        print("closed \(handle) explicitly")
    }

    deinit {                             // safety net: runs only if close() was never called
        _ = nativeClose(handle)
        print("deinit closed \(handle)")
    }
}

func run() throws {
    let db = DatabaseConnection(handle: 3)
    db.execute("UPDATE jobs SET done = 1")
    try db.close()                       // consumes db
    // db.execute("SELECT 1")            // error: 'db' used after consume

    let report = DatabaseConnection(handle: 4)
    let worker = consume report          // explicit hand-off; report is dead from here
    worker.execute("SELECT count(*) FROM jobs")
}                                        // worker's deinit closes handle 4

try run()

go deeper

for a junior

Recall that a consuming method uses up the value it is called on, so the caller cannot call anything on it afterwards.

for a middle

Explain why a consuming method that simply returns still runs deinit, and what discard self changes about that.

for a senior

Write close() in the right order, copy out, release, discard, then throw, and name the Swift 6.4 restrictions on discard, especially trivially destroyed storage.

for a principal

Judge where an explicit consuming close plus a deinit safety net beats deinit-only cleanup, given that only the explicit path can report a failure.

## Why `deinit` alone is not enough A noncopyable connection can close its native handle in `deinit`, and that runs exactly once. Two things are missing: - **Failure reporting.** A `deinit` cannot be declared `throws` and returns nothing, so a failed close is invisible to the caller. - **Timing the caller controls.** The connection should close when the caller says so, not when the last owner happens to go out of scope. The answer is an explicit terminal method, `close()`, that consumes the value. ## A consuming method ends the value Marking a method `consuming` gives it ownership of `self`. For the caller that means: 1. `try db.close()` moves `db` into the method, exactly as passing it to a `consuming` parameter would. 2. After the call `db` is dead. `db.close()` a second time fails with `'db' consumed more than once`; `db.execute(...)` fails with `'db' used after consume`. 3. Both are compile-time errors, so double-close and use-after-close never reach a running app. Inside the method there is a catch. If a consuming method simply returns, `self` is destroyed at the end of it, and destroying a value with a `deinit` runs that `deinit`. A `close()` that releases the handle and then returns would release it a second time in `deinit`. ## `discard self` skips the destructor `discard self` ends the lifetime of `self` **without** running `deinit`. The order inside `close()` matters: 1. Copy what you need out of `self` into locals, such as `let handle = self.handle`. 2. Call the native close and keep its status. 3. `discard self`. 4. Throw if the status was a failure, or return. Using a stored property after step 3 fails with `'self' used after consume`, which is why step 1 exists. On the error path the handle has still been released once and `deinit` still does not run, so a failed close never turns into a second close. The compiler enforces where `discard` may appear. In Swift 6.4: | Rule | What the compiler says when it is broken | |---|---| | only `self`, never another value | `you can only discard 'self'` | | only in a `consuming` method | `'discard' statement can only appear in consuming ...` | | the type must have a `deinit` | `'discard' has no effect for type ... unless it has a deinitializer` | | every stored property trivially destroyed | `can only 'discard' type ... if it contains trivially-destroyed stored properties at this time` | | from the type's own module | `can only 'discard' from the same module defining type ...` | The fourth rule bites in practice: adding `let label: String` to the connection makes `discard self` fail, because `String` needs destruction. SE-0390 lists lifting the trivially-destroyed restriction as a future direction. The proposal text also says "same file"; the Swift 6.4 compiler accepts `discard self` in an extension in another file of the same module. ## The `consume` operator `consume x` (SE-0366, Swift 5.9) ends the lifetime of a local binding or parameter at that point and yields its value: - `let worker = consume report` hands a noncopyable connection to a new name; `report` is dead from there on. - It works on **local `let` and `var` bindings and on parameters**. An `inout` parameter may be consumed only if it is reinitialized before the function returns. - It refuses globals and stored properties of a class. For a global, the diagnostic depends on where the variable is declared: a top-level variable of `main.swift` gets `'consume' cannot be applied to globals`, while a global declared in any other file gets `'consume' applied to value that the compiler does not support`, which swiftc 6.4 words as a compiler bug. - A `borrowing` parameter cannot be consumed: `'x' is borrowed and cannot be consumed`. - On a copyable value it ends the binding's lifetime early, so a later use is an error rather than a silent copy; on a bitwise-copyable type such as `Int` the compiler warns that it has no effect. ## Reading the example Explicit hand-off with `consume` is rarely needed for a noncopyable value, since `let worker = report` already moves it; writing `consume` documents the intent and also works for copyable values. In the snippet, handle 3 is closed explicitly and `deinit` does not run for it; handle 4 is never closed explicitly, so its `deinit` runs when `worker` goes away at the end of `run()`. Changing the first handle to one whose close fails makes `close()` throw `CloseError`, and still no `deinit` line is printed: the handle is released once on every path.

  • Why does `discard self` stop compiling once the Swift connection struct gains a `let label: String` property?
    Swift 6.4 allows `discard` only for types whose stored properties are all trivially destroyed, and `String` is not, so the compiler reports that it can only discard the type if it contains trivially-destroyed stored properties at this time. Keep only trivial fields, such as the `Int32` handle, in the type that discards, or let `deinit` do the cleanup instead.
  • Where can you apply Swift's `consume` operator, and where does the compiler refuse it?
    It applies to local `let` and `var` bindings and to parameters; an `inout` parameter must be reinitialized before the function returns. The compiler refuses globals (`'consume' cannot be applied to globals` for a top-level variable of `main.swift`, `'consume' applied to value that the compiler does not support` for a global declared in any other file), refuses class stored properties, and refuses a `borrowing` parameter because the caller still owns it. On an `Int` it only warns that it has no effect.

  • A deinit can be declared throws, so close errors can be reported from it.
  • discard self runs deinit immediately and then frees the value.
  • Calling close() twice on a noncopyable value is caught by a runtime flag.
  • discard can be applied to any noncopyable value from any module.
  • The consume operator works on globals and on class stored properties too.