Skip to content
Tutorials Center
My learning

Topics

Lesson 70 of 146 ยท Protocols and Generics

Noncopyable Types

Learn Swift noncopyable types: ~Copyable, ownership, consume, consuming and borrowing, deinit timing, take(), discard self and generics, with examples.

Almost everything you write in Swift can be copied. Assign an Int to another variable and you have two integers. Assign a struct and you have two structs. That is convenient, but it is a poor fit for things that must exist exactly once: an open file, a database connection, a lock you currently hold, a one-time ticket, a unique token. If such a value could be duplicated, two pieces of code might both close the file or both spend the ticket.

Swift 5.9 introduced noncopyable types for this job, and Swift 6 widened them so they work with generics, optionals and enums. You mark a type with ~Copyable ("not copyable"), and the compiler then tracks who owns each value. Ownership moves from one place to another, and the compiler proves at build time that nobody uses a value after it has been handed away. In this lesson you will learn the rules, read the real error messages, and see when this tool is worth reaching for.

Your first noncopyable type

Add ~Copyable after the type name. Structs, enums and (since Swift 6) generic parameters can be noncopyable. Classes cannot, because a class reference is copyable by nature; use a struct that owns the resource instead.

A noncopyable struct is allowed to have a deinit, just like a class. It runs exactly once, when the single owner goes away. That makes deinit a reliable place to release a resource.

Swift One owner, one deinit

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

Read the output from the top. opened ticket 1 appears once because there is only ever one ticket. The two inspect calls only look at the value. The line let b = a does not copy; it moves the ticket. From then on a is gone and b is the owner. When run finishes, b goes out of scope and deinit prints closed ticket 1 exactly once, before after run.

A noncopyable value is consumed when ownership leaves a variable: by assigning it, by passing it to a consuming parameter, by returning it, or by the explicit consume operator. After that the old variable cannot be used again, unless you assign it a new value.

Using a value after it moved

Because the compiler knows where ownership went, it can refuse code that would use a moved-from value. Try to read a after moving it:

Swift Use after move (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The compiler stops with main.swift:7:9: error: 'a' used after consume, and two notes point at let b = a (consumed here) and print(a.id) (used here). The notes are the useful part: they show you the exact move and the exact late use. The fix is to read what you need before moving, or to move into a new owner and keep using that one.

Notice what the program did not need: no reference counting and no runtime check. The proof happens at compile time, so noncopyable code can be as cheap as plain structs.

Why the examples use a function

You may have noticed that every example puts its logic in func run(). That is not style, it is a rule. In main.swift, variables declared at the top level are globals, and the compiler cannot track moves out of a global, because any function could touch it at any time.

Swift Moving a top-level variable (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The message is main.swift:7:9: error: cannot consume noncopyable stored property 'a' that is global. Wrap the code in a function (or a type's method) and local variables behave as described. Keep this in mind whenever you experiment with ~Copyable in a single-file program.

Saying who owns a parameter: borrowing, consuming, inout

For a copyable type, passing an argument quietly copies or retains it. A noncopyable type has no such default, so every parameter must state its ownership. There are three choices:

Modifier Meaning Caller afterwards
borrowing The function may read the value but may not keep or destroy it Still owns it
consuming The function takes the value and becomes responsible for it Has lost it
inout The function may read and change the value in place Still owns it

If you forget, the compiler says so. Here is a parameter with no modifier:

Swift Parameter without ownership (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The error reads main.swift:6:21: error: parameter of noncopyable type 'Ticket' must specify ownership, with three notes offering borrowing, inout and consuming. That is the whole menu.

A consuming parameter means the function owns the value for its duration. If it does not hand the value somewhere else, deinit runs when the function ends. A second call with the same variable is therefore illegal. Here the second take(a) is the problem:

Swift Consumed more than once (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

Now the error is main.swift:11:9: error: 'a' consumed more than once, with consumed here on the first call and consumed again here on the second. Choose borrowing when the function only needs to look, and reserve consuming for functions that really take over, such as "submit this order" or "close this file".

The consume operator and consuming methods

You can end a variable's life on purpose with consume x. This is also available for ordinary copyable values, where it is a hint to the optimizer, but it matters most here. A method can be marked consuming too: then self is taken from the caller.

Swift consume, consuming methods and deinit timing

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

Study the order of the output:

  • closed 7 prints before redeemed 7. The redeem method owns self, and after it computes its string the ticket dies at the end of the call, before print runs.
  • t = Ticket(id: 8) revives the variable t after its ticket was consumed. That is legal for var, and it is the only way a consumed variable can be used again.
  • show(t) consumes ticket 8, so closed 8 prints when show ends, before after show.
  • consume u moves ticket 9 into v, and v is destroyed when run ends, which is why closed 9 comes last.

This predictability is the point. With a class you cannot say exactly when the last reference disappears, but with a noncopyable value you can read it off the page.

Optionals, switch and take()

Since Swift 6, Optional can hold noncopyable values, so "maybe a ticket" is expressible. Two tools help you get the value out. switch consume x destroys the optional and binds its payload. take() is a method on Optional that returns the current value and leaves nil behind, which is the idiom for "hand over what I hold, if anything".

Swift Optionals of noncopyable values

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

take() is how a type with an optional resource field closes it exactly once: take the resource out, use it, let it die. The line cache == nil works even though the payload is noncopyable, because comparing with nil only inspects the "is there a value" tag.

Noncopyable generics

A generic parameter normally means "any copyable type". Writing <T: ~Copyable> widens that: it says "T may be copyable or noncopyable". The price is that, inside the function, you can only do what is allowed for noncopyable values, which means you cannot duplicate a T.

A common pattern is a wrapper that is noncopyable only when its contents are. The conditional conformance below says: if T is copyable, then Box<T> is copyable too. That is the same idea as in Conditional Conformance.

Swift A box that is copyable only if its content is

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

Box(3) copies happily, so both numbers and alias stay usable. Box(Resource()) is a noncopyable box, and the resource's deinit runs at the end of run, after made box. The standard library uses the same trick: Optional and Result are copyable if their payload is.

Cleaning up on purpose: discard self

Sometimes a consuming method finishes the job itself (closes the connection explicitly) and you do not want deinit to run a second time. Use discard self inside the method: it destroys the value without calling deinit.

Swift discard self skips deinit

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

Connection 1 prints only closing 1 explicitly; its deinit never runs. Connection 2 is simply dropped, so implicit cleanup 2 appears when run ends. Today discard self only works when every stored property is trivially destroyed, such as integers. If the type holds a String or an array the compiler refuses with error: can only 'discard' type 'Connection' if it contains trivially-destroyed stored properties at this time.

Noncopyable enums

Enums can be noncopyable too, and a switch consume hands you each payload with its ownership. This is excellent for state machines where each state owns different resources, for example .idle versus .open(Connection). Because a case's payload is moved out, you cannot accidentally keep using a connection after the machine moved to .closed.

Explicit copies for copyable types

Copyable types used with borrowing or consuming parameters can no longer copy implicitly. If you really need a copy, you write the copy operator. This surprises people the first time, so here it is:

Swift The copy operator on a borrowed value

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

It prints HELLO!. A borrowing parameter cannot be stored or returned without an explicit copy, which makes every duplication visible in the source.

When to use noncopyable types (and when not to)

Use ~Copyable when a value represents unique ownership: file descriptors, locks and lock guards, handles from C libraries, capabilities such as "permission to write", or one-shot tokens. In those cases the compiler turns "don't use it twice" into an error instead of a bug report. It also helps performance-sensitive code, because the compiler knows there is nothing to retain or release.

Avoid it for plain data. Noncopyable types cannot be used with many existing APIs (you cannot put them in an Array yet, and escaping closures cannot capture them), so they add friction. Prefer a class with deinit when you need shared ownership, and a plain struct when copying is harmless. See Value vs. Reference Semantics and Memory Management with ARC for the other side of the story.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does struct Token: ~Copyable change?

    ~Copyable removes the implicit copy. Assignment and argument passing move ownership, and the compiler proves the old variable is not used again.
  2. 2. After let b = a where a is a noncopyable value, what happens when you read a again?

    Moves are checked at compile time. The diagnostic marks where the value was consumed and where it was used afterwards.
  3. 3. Which parameter modifier lets a function read a noncopyable argument without taking it from the caller?

    borrowing gives read-only access while the caller keeps ownership. consuming takes the value away.
  4. 4. Why does a global let a = Ticket(id: 1) in main.swift fail with let b = a?

    Any code could access a global at any time, so the compiler cannot prove a move is safe. Put the code in a function.
  5. 5. What does discard self do inside a consuming method?

    Use it when the method has already done the cleanup that deinit would do.

Summary

  • ~Copyable removes implicit copying; assignment and passing move ownership instead.
  • The compiler proves at build time that a moved value is not used again ('a' used after consume, consumed more than once).
  • Noncopyable parameters need borrowing, consuming or inout.
  • deinit runs exactly once, when the single owner ends, so the timing can be read from the code.
  • consume x ends a variable explicitly; consuming methods take self; Optional.take() hands a value over and leaves nil.
  • Generics use <T: ~Copyable>, and wrappers can become copyable again with extension Box: Copyable where T: Copyable {}.
  • discard self skips deinit after manual cleanup, but only for trivially destroyed stored properties.
  • In main.swift, put noncopyable experiments inside a function, because globals cannot be consumed.
  • Reach for it for unique resources; do not use it for ordinary data.

Next: Parameter Packs