skip to content

In Swift, what does marking a database-connection struct `~Copyable` change, and what does the compiler do when you assign it to a second variable?

level: juniorimportance: nice to knowfreq 25%

answer

  1. suppresses an implicit protocol
  2. assignment becomes a move
  3. used after consume
  4. one owner, one deinit
  5. Array still requires Copyable

basics

~20 s

~Copyable removes a struct's implicit Copyable conformance, so each value has exactly one owner. Assigning it to another variable moves it, any later use of the original fails to compile, and its deinit can run only once.

solid answer

~40 s

Every Swift struct and enum is implicitly `Copyable`; writing `struct DatabaseConnection: ~Copyable` suppresses that, so the compiler never duplicates the value. `let owner = primary` moves ownership, and touching `primary` afterwards is a compile-time error, `'primary' used after consume`. Because there is only ever one owner, the struct can declare a `deinit` that closes the handle once, when the owner's lifetime ends. The price is reach: a noncopyable value cannot be an `Array` element or be stored in `Any`, a function parameter of its type must say `borrowing`, `consuming` or `inout`, and generic code accepts it only where a parameter is declared `~Copyable` (Swift 6.0). Noncopyable structs and enums arrived in Swift 5.9; classes cannot be `~Copyable`.

code

swift · 26 lines
swift
struct DatabaseConnection: ~Copyable {
    let handle: Int32

    init(handle: Int32) {
        self.handle = handle
        print("opened \(handle)")
    }

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

    deinit {
        print("closed \(handle)")
    }
}

func run() {
    let primary = DatabaseConnection(handle: 3)
    primary.query("SELECT 1")
    let owner = primary          // a move: ownership leaves `primary`
    owner.query("SELECT 2")
    // primary.query("SELECT 3") // error: 'primary' used after consume
}

run()

go deeper

for a junior

Recall that ~Copyable suppresses the implicit Copyable conformance and that assignment then moves the value. Quote the used after consume error and say it is a compile-time check.

for a middle

Explain why a single owner allows a deinit that closes a handle once, and which everyday places refuse a noncopyable value: arrays, Any and unannotated parameters.

for a senior

Argue when the friction pays off: native handles and one-shot tokens yes, plain models no. Show how you would hold several connections without Array.

for a principal

Weigh where in a codebase unique ownership removes a whole bug class, such as double close, against the cost to generic code and API ergonomics.

## What `~Copyable` actually says In Swift every struct and enum conforms to a marker protocol, **`Copyable`**, without anyone writing it. That conformance is what lets `let b = a` give you two independent values. Writing `~Copyable` after the type name **suppresses** that implicit conformance; it does not add a new protocol called "noncopyable". The result is a **noncopyable type**: a value of it can be moved from one owner to another, borrowed for a while, or destroyed, but never duplicated. - Introduced for structs and enums in **Swift 5.9** (SE-0390). - **Classes cannot be `~Copyable`**: the compiler answers `classes cannot be '~Copyable'`, because a class value is already a shared reference. - Generic parameters, protocols and the standard library's `Optional` learned to accept noncopyable types in **Swift 6.0** (SE-0427, SE-0437). ## Assignment is a move, checked at compile time With a copyable struct, `let owner = primary` copies. With a noncopyable one it **moves**: ownership leaves `primary` and arrives in `owner`. The compiler's ownership checker then tracks every later use. In the example below, un-commenting the last line produces: ``` error: 'primary' used after consume note: consumed here note: used here ``` The check is entirely static: there is no moved-from flag and nothing is tested at run time. The same rule covers passing the value to a parameter declared `consuming`, returning it, and storing it in a property: each is a move, and the source binding is dead afterwards. Reading the value does not move it. Calling an ordinary (non-`mutating`, non-`consuming`) method such as `primary.query("SELECT 1")` **borrows** `primary` for the duration of the call, so you can call it as many times as you like before the move. ## One owner, one cleanup The point of uniqueness is that a resource has exactly one place where it ends. For a database connection that means: 1. `init` opens the native handle. 2. Reads such as `query` borrow the value; they never duplicate the handle. 3. Whoever ends up owning the value last is where its lifetime ends. 4. The struct's `deinit` runs then, once, and closes the handle; the one way to skip it is a consuming method that ends the value with `discard self`. An ordinary struct cannot declare a `deinit` at all; that rule and the rest of deinitializer behaviour are covered with initializers and deinit. Here what matters is the consequence: double-close and use-after-close become **compile errors** rather than production incidents. ## What a noncopyable type gives up Much of Swift quietly copies. Every place that does is closed to a noncopyable type unless it was written to accept one. | Place | Copyable struct | `~Copyable` struct (Swift 6.4) | |---|---|---| | `let b = a` | copies | moves; `a` is dead | | `Array` / `Dictionary` element | allowed | rejected: element must be `Copyable` | | `Optional` payload | allowed | allowed since Swift 6.0 | | Stored in `Any` or a plain `any P` | allowed | rejected | | Function parameter | default convention | must say `borrowing`, `consuming` or `inout` | | Generic parameter `T` | allowed | only where declared `T: ~Copyable` | Trying `var pool: [DatabaseConnection] = []` yields `type 'DatabaseConnection' does not conform to protocol 'Copyable'`. The fixes are a fixed-size `InlineArray` (Swift 6.2), an `Optional` slot, or a class that owns the connections. Protocol conformances are possible only for protocols that themselves suppress `Copyable`; Swift 6.4 extended `Equatable`, `Comparable` and `Hashable` that way (SE-0499). ## When it is worth the friction - **Unique resources**: native handles, file descriptors, locks, one-shot tokens, anything whose cleanup must happen once. - **APIs that must not be called after a terminal step**: once a value is consumed, the compiler rejects further calls. - **Not ordinary models**: a `User` or a `CartItem` gains nothing and loses arrays, generics and `Any`. - **Compared with a class**: a class wrapper with a `deinit` also closes once, but every holder shares the same instance, so "already closed" has to be tracked with a flag and checked at run time. The noncopyable struct moves that check into the compiler and avoids a heap allocation for the wrapper. A good interview answer names the guarantee (single ownership, enforced at compile time) and the cost (the value no longer fits code that assumes copies), and reaches for `~Copyable` only where duplicating the value would be a bug.

  • What happens if you try to keep several noncopyable connections in an ordinary Swift array?
    It does not compile. `Array`'s `Element` carries the implicit `Copyable` requirement, so `[DatabaseConnection]` fails with `type 'DatabaseConnection' does not conform to protocol 'Copyable'`. Use a fixed-size `InlineArray`, whose element may be noncopyable since Swift 6.2, an `Optional` slot per connection, or a class that owns the connections and hands out borrows.
  • Can a noncopyable Swift struct conform to protocols?
    Only to protocols that suppress `Copyable` themselves. In Swift 5.9 a noncopyable type could conform to nothing but `Sendable`. Since Swift 6.0 a protocol can be declared `protocol Resource: ~Copyable`, and Swift 6.4 changed `Equatable`, `Comparable` and `Hashable` that way, so a noncopyable struct can implement `==` taking `borrowing` operands.

  • Marking a struct ~Copyable turns it into a reference type like a class.
  • let b = a on a noncopyable struct makes a shallow copy that shares storage.
  • Using a noncopyable value after a move is caught by a trap at run time.
  • A class can be declared ~Copyable to stop instances being shared.
  • Noncopyable connections can be stored in an ordinary Array.

Assumes Swift 6.4; ~Copyable structs and enums arrived in Swift 5.9, noncopyable Optional and generic parameters in Swift 6.0.