Michael Long
Aug 24, 2021

--

As the article demonstrates, if you have a custom reference type for which you want value semantics (class Ref in the article), then you do have to provide it.

But structs are value types and as such do implement COW semantics out of the box, whereby mutating a value in a copy doesn’t affect the original.

The traditional example…

var u1 = User(name: “Fred”)
var u2 = u1
u2.name = “Barney”
print(u1.name) // Fred
print(u2.name) // Barney

Interestingly, isKnownUniquelyReferenced used as shown in the Box struct demonstrates the behind the scenes ARC retain/release code Swift generates for you.

--

--

Michael Long
Michael Long

Written by Michael Long

I write about Apple, Swift, and SwiftUI in particular, and technology in general. I'm also a Lead iOS Engineer at InRhythm, a modern digital consulting firm.

Responses (1)