[swift-users] Understanding pass-by-value

Brent Royal-Gordon brent at architechies.com
Fri Nov 4 15:25:14 CDT 2016


> On Nov 4, 2016, at 9:45 AM, Ryan Lovelett <ryan at lovelett.me> wrote:
> 
> Just out of curiosity if I looked at the SIL, would that allow me to see
> any of that in action? Or would it be too opaque?

Maybe. What might be more directly useful is looking at the source for `Data` in Foundation:

<https://github.com/apple/swift/blob/master/stdlib/public/SDK/Foundation/Data.swift#L73>

You'll notice that `Data` has an internal property called `_wrapped` of type `_SwiftNSData`, which (if you jump up a few dozen lines) is a class. Since it's inside a class, the contents of that property won't be automatically copied.

Looking around a little more thoroughly, you might notice that `mutating` methods call `_applyUnmanagedMutation(_:)`: <https://github.com/apple/swift/blob/14b689dee1dcd4e5e7a8b5722ce343a57e10149d/stdlib/public/SDK/Foundation/Data.swift#L444>. If you search the codebase, you'll find the implementation of that method in a different file: <https://github.com/apple/swift/blob/c3b7709a7c4789f1ad7249d357f69509fb8be731/stdlib/public/SDK/Foundation/Boxing.swift#L173>.

The heart of the copy-on-write behavior is the call to `isKnownUniquelyReferenced(_:)`. This is a part of the standard library which is basically only used to implement copy-on-write. `isKnownUniquelyReferenced(_:)` returns `true` if your variable is the only one which has a strong reference to the object. If so, it's safe to mutate; if not, you'll need to make a copy so you don't affect any of the other instances sharing the object with you.

-- 
Brent Royal-Gordon
Architechies



More information about the swift-users mailing list