Noncopyable types (~Copyable)

Swift language Senior Swift 5.9+ iOS 17+ Reviewed By Alok Singh

Pick the fix

A file wrapper must never be copied, so the descriptor can't be closed twice. Which design?

Options
Hint 1 of 1

Which option makes copying impossible?

Choose an answer, then open Show answer below to check it.

Show answer

Answer: A struct File: ~Copyable with deinit { close(fd) } and consuming func close()

Correct. One owner, and deinit runs exactly once.

Why not the others?
  • B A final class with deinit. It works, but references can be shared freely, so ownership is unclear.
  • C A struct with an isClosed flag. Each copy has its own flag, so two copies can both close.
  • D An enum with an open and closed case. Copies are still allowed and can disagree.

30-second answer

A type marked ~Copyable can't be copied, only moved or borrowed. That gives unique ownership: exactly one owner, and a deinit that runs once. It fits resources like file descriptors, locks and tokens that must not be duplicated. Swift 6 extended generics and Optional to support noncopyable types.

Practise saying it · 30 s. No recording, just a timer

Explain ~Copyable.

Say your answer out loud, then check which of these points you covered:

  • Can't be copied
  • Unique ownership and deinit
  • borrowing / consuming

Deep dive

Parameters are borrowing (read-only) or consuming (takes ownership).

A consuming func close() ends the value's life, so it can't be used afterwards.

Noncopyable structs can have deinit, unlike normal structs.

Mutex and Atomic in Synchronization are noncopyable.

Common mistakes

  • Using a class when unique ownership is the point.
  • Expecting noncopyable types to work in every generic API.

Senior take & follow-ups

Seniors connect ~Copyable to resource safety and mention borrowing and consuming.

Follow-up questions

Think of your answer first, then open the hint.

  1. What does consuming mean?

    Show hint

    The function takes ownership; the caller can't use the value afterwards.

  2. Why is Mutex noncopyable?

    Show hint

    Copying a lock would split its state.

Suggest a fix if something here is wrong or out of date.