Noncopyable types and ownership: ~Copyable, consume, borrowing, consuming

suggest change

Every Swift type is copyable by default. Assigning a struct to another variable or passing it to a function makes a copy (see Structs are value types and Value Semantics). Classes are copied too, except that the copy is a second reference to the same object.

Some values should not be copied. A file descriptor, a lock, a database transaction or a one-time token has exactly one owner. If two copies of a File struct both close the same descriptor in deinit, the second close is a bug.

Swift lets you mark such types with ~Copyable ("not Copyable"). The compiler then tracks who owns each value and rejects any code that would copy it. This article covers:

The examples were compiled and run with Swift 6.4 on Windows:

swiftc -swift-version 6 main.swift -o main.exe

A noncopyable struct with deinit

Before Swift 5.9, only classes could have a deinit. A ~Copyable struct can have one too, because there is only ever one instance and it is clear when that instance dies:

struct FileHandle: ~Copyable {
    let fd: Int32
    let path: String

    init(path: String) {
        self.path = path
        self.fd = Int32(path.count)   // pretend we called open()
        print("open \(path) -> fd \(fd)")
    }

    func write(_ text: String) {
        print("fd \(fd): write \"\(text)\"")
    }

    deinit {
        print("close fd \(fd) (\(path))")
    }
}

func run() {
    let file = FileHandle(path: "log.txt")
    file.write("hello")
    file.write("world")
    print("end of run()")
}

run()
print("after run()")

Output:

open log.txt -> fd 7
fd 7: write "hello"
fd 7: write "world"
end of run()
close fd 7 (log.txt)
after run()

This gives you RAII-style cleanup without allocating a class object and without reference counting. Compare with deinit on classes in deinit, where the object dies only when the last reference goes away, and that can be hard to predict.

Assignment moves the value

With a copyable type, let other = file makes a copy. With a noncopyable type it moves the value: other is the new owner and file can't be used anymore.

func run() {
    let file = FileHandle(path: "log.txt")
    let other = file          // moves, does not copy
    other.write("via other")
    file.write("via file")
}
main.swift:21:9: error: 'file' used after consume
21 |     let file = FileHandle(path: "log.txt")
   |         `- error: 'file' used after consume
22 |     let other = file          // moves, does not copy
   |                 `- note: consumed here
23 |     other.write("via other")
24 |     file.write("via file")
   |     `- note: used here

The check is static. The compiler follows every path through the function, so it also catches a value that is consumed only on some paths, or consumed inside a loop:

struct Token: ~Copyable {
    let id: Int
}
func take(_ t: consuming Token) {}

func demo(flag: Bool) {
    let t = Token(id: 1)
    if flag {
        take(t)
    }
    print(t.id)

    let u = Token(id: 2)
    for _ in 0..<3 {
        take(u)
    }
}
error: 't' used after consume
    take(t)
         `- note: consumed here
    print(t.id)
          `- note: used here
error: 'u' consumed in a loop

borrowing, consuming and inout parameters

For a copyable parameter Swift picks the passing convention for you. For a noncopyable parameter you must say what the function does with the value:

func log(_ f: FileHandle) {
    f.write("x")
}
error: parameter of noncopyable type 'FileHandle' 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

The three options:

struct FileHandle: ~Copyable {
    let fd: Int32
    var bytesWritten = 0

    init(fd: Int32) {
        self.fd = fd
        print("open fd \(fd)")
    }

    mutating func write(_ text: String) {
        bytesWritten += text.utf8.count
        print("fd \(fd): write \(text.utf8.count) bytes")
    }

    deinit {
        print("close fd \(fd), \(bytesWritten) bytes written")
    }
}

func printInfo(_ f: borrowing FileHandle) {
    print("info: fd \(f.fd), \(f.bytesWritten) bytes")
}

func appendLine(_ f: inout FileHandle, _ line: String) {
    f.write(line + "\n")
}

func archive(_ f: consuming FileHandle) {
    print("archiving fd \(f.fd)")
}   // f is destroyed here, deinit runs

func demo() {
    var file = FileHandle(fd: 3)
    printInfo(file)
    appendLine(&file, "first")
    appendLine(&file, "second")
    printInfo(file)
    archive(file)
    print("done")
}
demo()

Output:

open fd 3
info: fd 3, 0 bytes
fd 3: write 6 bytes
fd 3: write 7 bytes
info: fd 3, 13 bytes
archiving fd 3
close fd 3, 13 bytes written
done

The handle is closed inside archive, before done is printed, because archive became the owner.

A borrowing parameter can't be moved out of the function:

func peek(_ f: borrowing FileHandle) {
    let g = f
    print(g.fd)
}
error: 'f' is borrowed and cannot be consumed
func peek(_ f: borrowing FileHandle) {
            `- error: 'f' is borrowed and cannot be consumed
    let g = f
            `- note: consumed here

Note that the code is wrapped in a demo() function. A global variable can't be consumed, because any code in the program could still access it:

error: cannot consume noncopyable stored property 'file' that is global

consuming methods and discard self

Methods have the same three conventions for self:

A consuming method is the natural way to write close(), commit() or finish(): after the call the value is gone, so the compiler prevents use-after-close.

Inside a consuming method, discard self ends the lifetime without running deinit. Use it when the method has already done the cleanup, or when it hands the resource to someone else:

struct FileHandle: ~Copyable {
    let fd: Int32
    var pending = 0

    init(fd: Int32) {
        self.fd = fd
        print("open fd \(fd)")
    }

    mutating func write(_ text: String) {
        pending += text.utf8.count
    }

    // ends the lifetime of self: the handle can't be used afterwards
    consuming func close() -> Int {
        print("flush \(pending) bytes to fd \(fd)")
        return pending
    }   // deinit runs here

    // gives up the descriptor without closing it
    consuming func release() -> Int32 {
        let fd = self.fd
        discard self   // deinit does not run
        return fd
    }

    deinit {
        print("deinit: close fd \(fd)")
    }
}

func demo() {
    var a = FileHandle(fd: 3)
    a.write("one")
    a.write("two")
    let n = a.close()
    print("closed, \(n) bytes")

    let b = FileHandle(fd: 4)
    let raw = b.release()
    print("released raw fd \(raw)")
}
demo()

Output:

open fd 3
flush 6 bytes to fd 3
deinit: close fd 3
closed, 6 bytes
open fd 4
released raw fd 4

Calling a.write("three") after a.close() is a compile error:

error: 'a' used after consume
    let n = a.close()
            `- note: consumed here
    a.write("three")
      `- note: used here

discard self has a limitation in current Swift: it works only if all stored properties are trivial (integers, pointers, other plain values). With a String or Array property you get:

error: can only 'discard' type 'FileHandle' if it contains trivially-destroyed stored properties at this time
note: type '[String]' cannot be trivially destroyed

The consume operator

consume x ends the lifetime of a local variable or parameter and gives you its value. It works on noncopyable values (where it is what an assignment does anyway) and also on ordinary copyable values:

func demo() {
    var names = ["Ann", "Bob"]
    let snapshot = consume names     // names is now uninitialized
    print(snapshot)
    // print(names)                  // error: 'names' used after consume
    names = ["Cid"]                  // a var can be reinitialized
    print(names)

    let big = [Int](repeating: 1, count: 1_000_000)
    var copy1 = big                  // copy: buffer is shared
    copy1.append(2)                  // copy-on-write: copies 1M elements
    var moved = consume big          // no copy, big is gone
    moved.append(2)                  // unique buffer: appends in place
    print(copy1.count, moved.count)
}
demo()

Output:

["Ann", "Bob"]
["Cid"]
1000001 1000001

For copyable types consume is mostly about performance and intent. Arrays, strings and dictionaries use copy-on-write. If another variable still refers to the buffer, the next mutation copies the whole buffer. consume guarantees the old variable is dead, so the buffer stays uniquely referenced. The optimizer often does this on its own, but consume makes it guaranteed, and the compiler reports any later use as an error.

borrowing and consuming on copyable parameters

You can also write borrowing and consuming on copyable parameters to control performance:

Inside a function, a borrowing copyable parameter can't be copied implicitly. You have to write copy explicitly:

func lengths(_ words: borrowing [String]) -> [Int] {
    words.map { $0.count }           // reading is fine
}

func store(_ words: borrowing [String]) -> [String] {
    return words                     // error: 'words' is borrowed and cannot be consumed
}

The fix is return copy words. That makes the copy visible in the code.

Noncopyable enums

Enums can be ~Copyable too, and their payloads can be noncopyable. switch on a borrowed value reads it. switch consume takes the payload out:

struct Token: ~Copyable {
    let id: Int
    deinit { print("token \(id) destroyed") }
}

enum Slot: ~Copyable {
    case empty
    case holding(Token)
}

func describe(_ s: borrowing Slot) -> String {
    switch s {
    case .empty: return "empty"
    case .holding(let t): return "holding token \(t.id)"
    }
}

func open(_ s: consuming Slot) -> Token? {
    switch consume s {
    case .empty: return nil
    case .holding(let t): return t
    }
}

func demo() {
    let s = Slot.holding(Token(id: 1))
    print(describe(s))
    if let t = open(s) {
        print("got token \(t.id)")
    }
    print("end of demo")
}
demo()

Output:

holding token 1
got token 1
token 1 destroyed
end of demo

The function open returns Token?, an Optional of a noncopyable type. That is allowed since Swift 6.0.

Optional of a noncopyable type

A noncopyable value stored in an optional property is a common pattern: "a connection that may or may not be open". Two things work differently from copyable optionals:

struct Connection: ~Copyable {
    let host: String
    func send(_ msg: String) { print("\(host) <- \(msg)") }
    deinit { print("disconnect \(host)") }
}

struct Client: ~Copyable {
    var connection: Connection?

    mutating func connect(to host: String) {
        connection = Connection(host: host)   // old one, if any, is destroyed
    }

    func ping() {
        switch connection {
        case .some(let c): c.send("ping")
        case .none: print("not connected")
        }
        connection?.send("ping again")
    }

    mutating func disconnect() -> Connection? {
        connection.take()                     // leaves nil behind
    }
}

func demo() {
    var client = Client(connection: nil)
    client.ping()
    client.connect(to: "a.example")
    client.ping()
    client.connect(to: "b.example")
    if let c = client.disconnect() {
        c.send("bye")
    }
    client.ping()
    print("end of demo")
}
demo()

Output:

not connected
a.example <- ping
a.example <- ping again
disconnect a.example
b.example <- bye
disconnect b.example
not connected
end of demo

Client has to be ~Copyable itself, because it stores a noncopyable property. A copyable struct can't contain a noncopyable value. The same rule applies to Mutex and Atomic, which are noncopyable, as explained in Mutex and Atomic with the Synchronization module.

Noncopyable generics

A generic parameter <T> implicitly requires T: Copyable. So does Array, Any and most of the standard library:

func show<T>(_ value: borrowing T) { print(value) }

let t = Token(id: 1)
show(t)
let arr = [Token(id: 2)]
let s: Any = Token(id: 3)
error: global function 'show' requires that 'Token' conform to 'Copyable'
note: 'where T: Copyable' is implicit here
error: generic struct 'Array' requires that 'Token' conform to 'Copyable'
error: value of type 'Token' does not conform to specified type 'Copyable'

Since Swift 6.0 you can suppress that implicit requirement with T: ~Copyable. It means "T may be noncopyable", not "T must be noncopyable". Code in such a generic must then treat values of T as noncopyable: borrow, consume or move them, never copy them.

struct Token: ~Copyable {
    let id: Int
    deinit { print("token \(id) destroyed") }
}

// T may or may not be copyable
struct Box<T: ~Copyable>: ~Copyable {
    var value: T
    init(_ value: consuming T) { self.value = value }
    consuming func unwrap() -> T { value }
}

// Box is copyable when T is
extension Box: Copyable where T: Copyable {}

extension Box where T: ~Copyable {
    func with<R>(_ body: (borrowing T) -> R) -> R { body(value) }
}

func swapValues<T: ~Copyable>(_ a: inout T, _ b: inout T) {
    let tmp = consume a
    a = consume b
    b = tmp
}

func demo() {
    let b1 = Box(Token(id: 1))
    print(b1.with { $0.id })
    let t = b1.unwrap()
    print("unwrapped \(t.id)")

    let b2 = Box(42)
    let b3 = b2              // fine: Box<Int> is Copyable
    print(b2.value, b3.value)

    var x = Token(id: 10), y = Token(id: 20)
    swapValues(&x, &y)
    print(x.id, y.id)
}
demo()

Output:

1
unwrapped 1
42 42
20 10
token 10 destroyed
token 20 destroyed
token 1 destroyed

Points to note:

Noncopyable protocols

A protocol can also opt out of the implicit Copyable requirement. Then both copyable and noncopyable types can conform:

protocol Resource: ~Copyable {
    var name: String { get }
    consuming func close()
}

struct TempFile: Resource, ~Copyable {
    let name: String
    consuming func close() { print("closing \(name)") }
    deinit { print("delete \(name)") }
}

struct Label: Resource {          // copyable types can conform too
    let name: String
    func close() { print("nothing to close for \(name)") }
}

func useAndClose<R: Resource & ~Copyable>(_ r: consuming R) {
    print("using \(r.name)")
    r.close()
}

func demo() {
    useAndClose(TempFile(name: "a.tmp"))
    useAndClose(Label(name: "title"))
    let other = TempFile(name: "b.tmp")
    print("not closing \(other.name) explicitly")
}
demo()

Output:

using a.tmp
closing a.tmp
delete a.tmp
using title
nothing to close for title
not closing b.tmp explicitly
delete b.tmp

The generic constraint has to repeat ~Copyable (R: Resource & ~Copyable). Without it, useAndClose would accept only copyable resources. In the same way, a plain any Resource box holds only copyable values. let r: any Resource = TempFile(name: "a") fails with error: value of type 'TempFile' does not conform to specified type 'Copyable'. Write generic or some code for noncopyable types (see Opaque and existential types: some and any).

Limitations

When to use ~Copyable

For ordinary data, keep using copyable structs. They are simpler to work with. Copy-on-write already makes copies cheap, and you can use consume and borrowing / consuming parameters to fine-tune hot paths without making the whole type noncopyable.

Another new Swift 6 feature, typed throws (throws(MyError)), goes well with consuming methods. A consuming func commit() throws(DBError) tells the caller both that the transaction is gone and exactly which error it can get.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents