Introduction to Non-Copyable types


You’re more of a video kind of person? I’ve got you covered! Here’s a video with the same content than this article 🍿


Non-Copyable structs and enums is a feature that’s been recently added to Swift.

It’s a very powerful feature that allows you to impose strong restrictions on how a value type is allowed to be handled.

So in this article I want to introduce you to this new concept and show you how it can help you make your code safer.

First, let’s talk about how we’ve always been allowed to handle value types in Swift.

From the moment that a value type has been stored in a variable or a constant, nothing prevents us from making copies of that value into other variables or constants:

Most of the time, this behaviour is exactly what we want, but there could be situations where we’d like to impose that a value can never be copied.

For instance, this would make perfect sense if a value was meant to be used a single time only.

And this is when non-copyable types come into play!

This is the syntax to make a struct non-copyable:

It might look a bit weird, but what it says is that it removes the implicit conformance to the protocol Copyable.

And as you can see, as soon as we’ve made our type non-copyable, it’s no longer possible to make a copy of it and keep using both the copy and the original:

We’re still allowed to assign the value to a different variable, but when we do so, it consumes the original variable, making it unusable past that point.

But what’s really nice is that this behaviour can also be applied to the parameter of a function.

Let’s say that we want a function that takes a Token as its argument, and we also want that once a Token has been passed to the function, it can no longer be used after that.

To implement this, we just need to mark the argument of the function with the new keyword consuming:

This way, once we’ve called the function and passed the value as its parameter, it then becomes impossible to reuse that value later in the code:

And so we’ve effectively implemented a system where each Token can only be used once, and the compiler will make sure that this rule is enforced.

That’s all for this article, I hope that you’ve enjoyed discovering this new feature of Swift!

Don’t forget that this was just an introduction: there’s still a lot more to be said about non-copyable types.

Here’s the code if you want to experiment with it:

import Foundation

struct Token: ~Copyable {
    var value: String
}

func getToken() -> Token {
    // ...
}

func use(token: consuming Token) {
    // ...
}

let token = getToken() // ❌ 'token' used after consume

use(token: token)

print(token.value)
Next
Next

How to hide private information