skip to content

In Swift 6, how do you write a generic container or enum that holds a noncopyable connection, and how does switching over it work?

level: seniorimportance: nice to knowfreq 12%

answer

  1. generic parameters assume Copyable
  2. suppress it with ~Copyable
  3. conditionally Copyable container
  4. Optional.take()
  5. borrowing switch versus switch consume

basics

~20 s

Declare Resource: ~Copyable, make the container ~Copyable, and add extension Slot: Copyable where Resource: Copyable. Since Swift 6.0, Optional.take() moves a payload out, and a switch over a borrowed noncopyable enum borrows unless you write switch consume.

solid answer

~40 s

Every generic parameter carries an implicit `Copyable` requirement, so `struct Slot<Resource>` rejects a noncopyable connection with `generic struct 'Slot' requires that 'DatabaseConnection' conform to 'Copyable'`. Since Swift 6.0 you write `Resource: ~Copyable`, which allows both kinds; a type that stores such a value must itself be `~Copyable`, and `extension Slot: Copyable where Resource: Copyable` makes it copyable again for `Int`. Inside, a `Resource` can be borrowed or moved, never copied. `Optional` follows the same pattern, so `resource.take()` moves the value out and leaves `nil`. Plain extensions still assume `Copyable` unless they add `where Resource: ~Copyable`. Switching over a borrowed noncopyable enum binds payloads as borrows; `switch consume link` lets a case move its payload out.

code

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

// Resource: ~Copyable removes the default Copyable requirement on the parameter.
struct Slot<Resource: ~Copyable>: ~Copyable {
    private var resource: Resource?

    init(_ resource: consuming Resource) { self.resource = consume resource }

    mutating func checkOut() -> Resource? {
        resource.take()                  // moves the value out and leaves nil behind
    }
}

// Copyable again whenever the element is copyable.
extension Slot: Copyable where Resource: Copyable {}

func run() {
    var slot = Slot(DatabaseConnection(handle: 3))
    if let connection = slot.checkOut() {
        print("using \(connection.handle)")
    }                                    // connection's deinit runs here
    print(slot.checkOut() == nil)

    let counter = Slot(42)
    let copy = counter                   // fine: Slot<Int> is Copyable
    _ = (counter, copy)
}

run()

go deeper

for a junior

Recall that generic parameters require Copyable by default and that writing ~Copyable on the parameter lifts that requirement.

for a middle

Explain why the container must become ~Copyable and how a conditional Copyable extension restores copying for ordinary elements.

for a senior

Show Optional.take() moving a connection out, the extension default, and when a switch must consume the enum to hand its payload back.

for a principal

Decide whether a shared generic utility should support noncopyable elements, given the cost of auditing every extension and the newer-runtime requirement.

## The requirement nobody writes In Swift every generic parameter, every protocol and every existential quietly requires **`Copyable`**. That is why `struct Slot<Resource>` can copy a `Resource` without asking, and why `Slot(DatabaseConnection(handle: 3))` fails with: ``` error: generic struct 'Slot' requires that 'DatabaseConnection' conform to 'Copyable' ``` **Swift 6.0** (SE-0427) lets you **suppress** that default by writing `~Copyable` on the parameter. The meaning is easy to get backwards: `Resource: ~Copyable` does **not** say "Resource must be noncopyable". It removes a requirement, so both `Int` and a noncopyable connection are accepted. The cost lands on the generic code, which may no longer copy a `Resource`. ## Writing a container that accepts both 1. Declare the parameter `Resource: ~Copyable`. 2. Declare the container `~Copyable` too. Leaving it out fails with `stored property 'resource' of 'Copyable'-conforming generic struct 'Slot' has non-Copyable type 'Resource?'`. 3. Add `extension Slot: Copyable where Resource: Copyable {}` so that `Slot<Int>` copies as before. 4. Inside, treat a `Resource` like any noncopyable value: take it as `consuming` to store it, borrow it to read it, move it out to return it. The standard library declares `Optional`, `Result` and `InlineArray` in this same conditionally copyable shape. ## Optional and `take()` SE-0437 (Swift 6.0) generalised `Optional` to `Optional<Wrapped: ~Copyable>`, copyable only when `Wrapped` is. A noncopyable connection can therefore sit in an optional stored property, and `take()` becomes the key move operation: its documentation says it returns the wrapped value "while also setting the instance to `nil`". A slot that hands a connection out is one line, `resource.take()`, and the connection's `deinit` runs when the caller's `if let` binding ends. ## Extensions and protocols - **Extensions assume `Copyable`.** `extension Slot { var isEmpty: Bool ... }` is available only on copyable instantiations; calling it on `Slot<DatabaseConnection>` fails with `property 'isEmpty' requires that 'DatabaseConnection' conform to 'Copyable'`. Write `extension Slot where Resource: ~Copyable` for members that must work for both. - **Protocols** opt in the same way: `protocol Pooled: ~Copyable` accepts noncopyable conformers. Swift 6.4 did this for `Equatable`, `Comparable` and `Hashable` (SE-0499). - **Run time**: the 6.0 changelog says full functionality needs the newer Swift 6 runtime, and casting a type that has noncopyable generic arguments needs a recent enough OS on Apple platforms. ## Switching over a noncopyable enum An enum can be `~Copyable` and carry a noncopyable payload, such as `case connected(DatabaseConnection)`. Since **Swift 6.0** (SE-0432) a `switch` does not have to consume it: | Form | What happens to the enum | Payload bindings | |---|---|---| | `switch link` on a borrowed value | untouched; usable after the switch | borrows, read-only | | `switch consume link` | consumed by the switch | owned; a case may move the payload out | So a `status(_ link: borrowing Link)` function can describe the state, while `detach(_ link: consuming Link) -> DatabaseConnection?` returns the payload of `.connected`. Returning a payload from a borrowing switch fails: the enum is still the caller's, so its contents cannot leave. Swift 6.4 also rejects one case label with several patterns, such as `case .idle, .failed:`, on a noncopyable value with `matching a non-'Copyable' value using a case label that has multiple patterns is not implemented`; split the label or use `default`. ## Newer pieces, in one line each - `InlineArray` (Swift 6.2) is a fixed-size container generic over `Element: ~Copyable`. - `UniqueBox` (Swift 6.4, SE-0517) is a standard-library box that uniquely owns one value on the heap, itself `~Copyable`. - `Array`, `Dictionary` and `Set` still require copyable elements. ## Reading the examples In the first example, `Slot(DatabaseConnection(handle: 3))` moves the new connection into the slot through a `consuming` initializer. `checkOut()` is `mutating` because `take()` changes the stored optional to `nil`; the returned connection is owned by the `if let` binding, so `closed 3` prints as soon as that block ends, before the second `checkOut()` reports `true` for an empty slot. `Slot(42)` shows the conditional conformance at work: with `Int` inside, `let copy = counter` is an ordinary copy. In the second example, `status(link)` borrows, so `link` is still available for `detach(link)`, which consumes it. The `.connected` case moves the payload into the return value; the caller's `if let c` then owns the connection, and `closed 8` prints when that binding ends, before `done`.

  • Why does a member added in a plain `extension Slot` refuse `Slot<DatabaseConnection>`?
    Extensions of a type whose parameter is `~Copyable` still assume `Copyable` unless they say otherwise, so the member exists only where `Resource` is copyable; the compiler reports that it requires `DatabaseConnection` to conform to `Copyable`. Write `extension Slot where Resource: ~Copyable` for members that must work for both kinds, and keep copy-dependent ones in the default extension.
  • Why can't a borrowing switch over a noncopyable Swift enum return its `.connected` payload?
    A borrowing switch leaves the enum owned by the caller, so its payload bindings are borrows too; returning one would move a value the function does not own, and the compiler reports that the parameter is borrowed and cannot be consumed. Take the enum as `consuming` and write `switch consume link` to move the payload out.

  • Generic parameters accept noncopyable types unless you add a Copyable constraint.
  • Writing T: ~Copyable means T must be a noncopyable type.
  • A struct storing a ~Copyable T can still be Copyable unconditionally.
  • Optional cannot wrap a noncopyable type, so use a flag plus storage.
  • Switching over a noncopyable enum always consumes it.

Assumes Swift 6.4; ~Copyable generic parameters, noncopyable Optional and Result, and borrowing switches over noncopyable enums arrived in Swift 6.0, UniqueBox in Swift 6.4.