Adam Esterline's Blog

Swift for Rustaceans - Borrow Checker

Swift Rust S4R

I like learning new programming languages and it has been a few years since I learned a new one. Recently I have become interested in Swift. Swift got on my radar when I saw the One Billion Row Challenge (1BRC) video on the NSScreencast. I had thought about Swift as a language for iOS applications. I didn't realize that it could be used for server or CLI applications. The 1BRC video got me thinking about how Swift compared to Rust.

Swift for Rustaceans (S4R)

As I am learning Swift, I thought it would be fun to capture my impressions, in bite-sized chunks, as it compares to Rust. The tag S4R will follow my journey. I will likely get things wrong as I learn, but I'll provide my impressions on Swift as it compares to Rust. My impressions are heavily influenced by my Rust experience. Things that seem "easier" to me in Swift may not be easier for someone who doesn't already know Rust.

Borrow checker

Swift mostly just works without having to think about a borrow checker. Most types in Swift are value types, which are copied when you pass them around. The following Swift code compiles and runs fine. In Rust, this code would not compile. The name variable would not be available to print after calling greet. The ownership of name is passed to greet when greet is called.

let name = "Adam"

let greeting = greet(name)

print(name)
print(greeting)

Swift's value copy semantics likely make the resulting program slower than the Rust version, but copy by default does seem easier to learn as a beginner. It's common in Rust to tell beginners to clone as much as needed when you are first battling the borrow checker. It feels like Swift bakes this advice in as a default.

Swift can behave in a similar way to Rust's borrow checker using the borrowing and consuming keywords. I haven't explored these too deeply yet, but they seem like a way to use Rust's borrow semantics in Swift.