skip to content

In Swift, when a function takes a noncopyable database connection, how do `borrowing` and `consuming` parameters differ, and why must you choose one?

level: seniorimportance: should knowfreq 25%

answer

  1. who owns it after the call
  2. lend versus hand over
  3. inits and setters consume by default
  4. no default for noncopyable
  5. explicit copy for a borrow

basics

~20 s

A borrowing parameter lends the value for the call and the caller still owns it afterwards; a consuming parameter transfers ownership, so the callee stores or destroys it. Noncopyable parameters have no default, so Swift requires borrowing, consuming or inout.

solid answer

~50 s

For copyable arguments Swift picks a convention for you: initializers and property setters consume their parameters, other functions borrow them, and copies are inserted where needed. A noncopyable type cannot be copied, so the compiler refuses to guess: `func describe(_ c: DatabaseConnection)` fails with `parameter of noncopyable type 'DatabaseConnection' must specify ownership`. Write `borrowing` when the function only reads, as logging or a query does, and the caller keeps the connection. Write `consuming` when the function keeps or ends it, such as checking it into a pool or closing it; the caller's binding is dead after the call. Write `inout` to mutate it and hand it back. On copyable types the modifiers tune ownership traffic, and a `borrowing` parameter becomes not implicitly copyable, so storing a borrowed `String` needs `copy name`. Either modifier is part of a public function's ABI.

code

swift · 33 lines
swift
struct DatabaseConnection: ~Copyable {
    let handle: Int32
    deinit { print("closed \(handle)") }
}

func describe(_ connection: borrowing DatabaseConnection) -> String {
    "connection \(connection.handle)"            // reads only; caller keeps ownership
}

final class ConnectionPool {
    private var spare: DatabaseConnection?

    func checkIn(_ connection: consuming DatabaseConnection) {
        spare = consume connection               // ownership moves into the pool
    }
}

func label(_ name: borrowing String) -> String {
    let kept = copy name                         // a borrowing parameter needs an explicit copy
    return kept.uppercased()
}

func run() {
    let pool = ConnectionPool()
    let c = DatabaseConnection(handle: 7)
    print(describe(c))
    print(describe(c))                           // still ours after a borrow
    pool.checkIn(c)                              // consumed here
    // print(describe(c))                        // error: 'c' used after consume
    print(label("pool"))
}

run()

go deeper

for a junior

Recall that borrowing lends the value for the call while consuming hands it over for good, and that a noncopyable parameter must name one of them.

for a middle

Explain the default conventions for copyable parameters, inits and setters consume and other functions borrow, and why copies hide them.

for a senior

Choose the modifier from what the callee does with a connection, read the borrowed-cannot-be-consumed error, and know that borrowing needs explicit copy.

for a principal

Treat ownership modifiers on public APIs as ABI decisions: fix them deliberately in an ABI-stable library, because changing one later breaks binaries.

## Two conventions Swift already uses Every argument is passed under an **ownership convention**. Under **borrowing**, the caller keeps ownership and guarantees the value stays alive for the call; the callee may read it but not keep it. Under **consuming**, ownership moves into the callee, which must store the value somewhere or destroy it before returning. SE-0377 describes the defaults Swift picks for copyable parameters: - **Initializers and property setters consume** their parameters, because they usually store them in the new value. - **Every other function borrows**, because that is cheaper in most code. - Where a borrowed value has to be kept, or a consumed value is still needed by the caller, the compiler **inserts a copy**. The last rule is why the defaults are invisible for copyable types: a copy papers over any mismatch. ## Why noncopyable parameters need a modifier A `~Copyable` value cannot be copied, so the compiler cannot paper over a mismatch, and it will not guess which convention you meant. Leaving the modifier off is an error with three suggested fixes: ``` error: parameter of noncopyable type 'DatabaseConnection' must specify ownership note: add 'borrowing' for an immutable reference note: add 'inout' for a mutable reference note: add 'consuming' to take the value from the caller ``` | Modifier | Caller after the call | Callee may | Typical use for a connection | |---|---|---|---| | `borrowing` | still owns it, may keep using it | read it, call non-consuming methods | logging, running a query | | `consuming` | binding is dead; later use is `used after consume` | store it, move it on, or let it be destroyed | checking it into a pool, closing it | | `inout` | owns it again, possibly modified | mutate it in place | updating stored session state | Neither `borrowing` nor `consuming` changes the call site: you write `pool.checkIn(c)`, not `&c` or `consume c`. Only `inout` arguments keep their `&` marker. ## Working with a borrowed value Inside the function a `borrowing` parameter is read-only and cannot leave: 1. Reading properties and calling ordinary methods is fine. 2. Trying to store or move it fails with `'c' is borrowed and cannot be consumed`. 3. Capturing it in an escaping closure fails with `'c' cannot be captured by an escaping closure since it is a borrowed parameter`. 4. For a **copyable** type such as `String`, you may keep a duplicate, but only by writing `copy name`. A plain `let kept = name` is rejected, because the modifier switches implicit copying off for that binding. ## Working with a consumed value A `consuming` parameter is owned by the function, so it can be stored, returned or passed on: - `spare = consume connection` moves it into a property. Assigning a noncopyable parameter into an `Optional` property without `consume` is rejected with `implicit conversion to 'DatabaseConnection?' is consuming`, and the note asks you to add `consume`. - If the function does none of these, the value is destroyed at the end of the call and its `deinit` runs there. - The caller's original binding is dead afterwards, which is the point: a connection checked into the pool cannot also be used by the screen that handed it over. ## On copyable types, and in public APIs For copyable parameters the modifiers do not change what a correct program computes; The Swift Programming Language says they affect "only the relative efficiency of particular usage patterns, not correctness". Use `consuming` when the callee keeps the value and the caller is done with it, as in a builder's `append`. Use `borrowing` when the callee only inspects a large value. Two costs to know: - A `borrowing` parameter needs explicit `copy` wherever the body keeps it. - SE-0377: the modifiers change the calling convention, so adding or changing one on a public function in an ABI-stable library breaks ABI, except for trivial types such as `Int`. ## Reading the example `describe(c)` is called twice because each call only borrows `c`. `pool.checkIn(c)` is the last use: ownership moves into the pool's `spare` property, and the connection's `deinit` prints `closed 7` only when the pool itself is released at the end of `run()`. Moving the `describe` call below `checkIn` turns a working program into a compile error, which is the whole value of the modifier: the caller cannot keep using a connection it has given away.

  • What does the Swift error `'c' is borrowed and cannot be consumed` mean, and how do you fix it?
    The function declared `c` as `borrowing` but then tried to move it, by storing it, returning it or passing it to a `consuming` parameter. The caller still owns the value, so the callee cannot give it away. Change the parameter to `consuming` if the function really takes ownership, or, for a copyable type, keep a duplicate with `copy c`.
  • Does adding `consuming` to a parameter of a public Swift function break its clients?
    At source level, callers of a copyable parameter need no change, because call sites are written the same way. At binary level it changes the calling convention, so SE-0377 says it breaks ABI for ABI-stable libraries, except for trivial types such as `Int` where the modifier has no practical effect.

  • A borrowing parameter can be stored by the callee and used after it returns.
  • A consuming parameter copies the value so the caller keeps its own.
  • A noncopyable parameter defaults to borrowing like any other function parameter.
  • Callers must write consume or & at the call site for consuming parameters.
  • On copyable types, switching borrowing to consuming changes the program's results.