Swift
Borrowing and consuming, the ownership of values
You've read thisOwnership tells the compiler how you plan to use a value.
borrowing - take a value temporarily
consuming - take the value so the original owner cannot keep using it
import Foundation
func orderFood() {
let food = Food(name: "🥐")
photograph(food)
eat(food)
photograph(food)
}
func photograph(_ food: borrowing Food) {
print("Taking a photo of the \(food.name)...")
}
func eat(_ food: consuming Food) {
print("Eating \(food.name)...")
}
struct Food: ~Copyable { // Note: this is non-copyable
let name: String
}‘Photographing’ only borrows the food temporarily, but ‘eating’ the food means no one else can have access to it when we’re done.
With these simple keywords we can give the compiler enough information to catch mistakes at compile time instead of letting them become a 💥 at runtime.
More detail
Imagine in our code that instead of a 🥐 we were dealing with a file on disk.
Instead of photographing our file we want to read the contents of it, and, instead of eating, we’ll close access to the file.
Without this explicit ownership we might end up writing a function which tried to read the file after closing it, causing a failure for the user.
In the world where dealing with a file could lead to runtime failures for our users, this ownership can be moved to compile time with minimal change to our code. It also allows anyone reading the code to know how their value might be used.
We can add the consuming and borrowing keywords to our parameters to tell the compiler how we plan to use the value in our functions, giving the compiler enough information to give us compile time errors 👏🏻.
// The consume keyword
// Removing the ‘borrowing’ or ‘consuming’ keyword from the params gives a new compiler error
Deep dive
// Speed benefits, manifesto details
// arc overhead without this
—
https://github.com/swiftlang/swift/blob/main/docs/OwnershipManifesto.md
https://infinum.com/blog/swift-ownership/
WWDC vids
Finished the deep dive?
You made it to the end.
Mark this bite as read once you have worked through the full piece. It is a small way to keep track of what you have genuinely finished.
More in this area
Keep the thread going.
Jump sideways into the related ideas that sit closest to this piece and keep the same mental context alive.