Consume operator in Swift


Greetings, traveler!

Imagine a scenario where you have to pass a model through multiple functions. Consider this example:

struct Model {
    let name: String
}

func firstMethod() {
    let model = Model(name: "ModelName")
    secondMethod(model: model)
}

func secondMethod(model: Model) {
    print(model.name)
}

firstMethod()

The issue is that the initial model created in the first function will be released from memory only after being used in the second function.

The consume operator, introduced in Swift 5.9, can prevent unnecessary memory allocations. It can be used with copyable types. Check out this example:

struct Model {
    let name: String
}

func firstMethod() {
    let model = Model(name: "ModelName")
    let copy = consume model
    
    secondMethod(model: copy)
}

func secondMethod(model: Model) {
    print(model.name)
}

firstMethod()

What is going on here? First, we create a model instance. Second, we create a copy of it. Using the consume operator terminates the first model lifespan. After that, we cannot use it anymore.

func firstMethod() {
    let model = Model(name: "ModelName") // ❌ Error: 'model' used after consume
    let copy = consume model
    
    print(model)
    secondMethod(model: copy)
}

Sure thing, you can use this operator in other cases. For example, you can write it to prevent yourself from using an object in code after being copied.

Conclusion

There is always room for additional code optimization.