Why structs over classes?
Because structs typically have value semantics [1], and I generally prefer value semantics over reference semantics.
IMPORTANT This is a general preference, not a strict rule. Some things are best modelled by reference semantics, and I use a class for those. For example, a TCP connection has its own independent identity — you can’t copy a TCP connection like you would, say, an
Int
— and thus I’d use a class for that.
Isn’t it more efficient to pass by reference than by value?
That depends. In many cases the Swift compiler can optimise away the copy, passing the struct by reference. In cases where it doesn’t, you can use a technique called copy on write (COW) to minimise the cost of copies that aren’t specifically mutated. However, I view COW as an optimisation, and I would only deploy it if I was absolutely certain (for example, I had hard evidence from the profiler) that it was necessary.
I've always thought of structs as appropriate for very small things only, like
CGSize
or
NSRange
.
That’s certainly the standard approach for Objective-C code, but Swift is not Objective-C and there are substantial benefits to be had by exploiting Swift’s features. Structs are just one of those features, and that’s not even the most important one IMO. I find that Swift’s enums have had the biggest impact on how I program.
Share and Enjoy
—
Quinn “The Eskimo!”
Apple Developer Relations, Developer Technical Support, Core OS/Hardware
let myEmail = "eskimo" + "1" + "@apple.com"
[1] It is possible to create a struct that doesn’t have value semantics, although that’s not something I’d recommend. It’s also possible to create a class that does have value semantics, but only if you make it immutable.