Wednesday, February 3, 2016

Value vs. Reference in Swift

David Owens II:

This is a general concern of mine in Swift: how to actually know what has value vs. reference semantics.

Swift adds let and var, which fixes one problem. But there is no way to see what is a struct or a class, which adds another. It’s even more complicated in the context of the proposal to remove the “NS” prefix from Foundation class names.

Nate Cook:

As an example, the seemingly similar Set and CountedSet types produce different results from nearly identical code. Swift’s Set type has value semantics, so changes to a copy don’t affect the original Set instance […] CountedSet (née NSCountedSet), on the other hand, uses reference semantics, so changes to a copy of an instance. This is true whether the copy is an explicit one made via assignment or the implicit copy made when calling a function with CountedSet as a parameter. This example shows how nearly code nearly identical to the above produces very different results […]

1 Comment RSS · Twitter

But even a struct can have reference semantics if it includes a class reference and stores its data in the class. Or it can have hybrid semantics: store some data within the struct and some data behind a class reference. You never really know what semantics a type has unless you look at its documentation or implementation.

Although in this case here it'd be a bit silly to have `Set` and `CountedSet` behave so differently: it breaks too many expectations. I understand why they want to remove the NS prefix, but there's plenty of cases (like this one) where it's a bad idea.

Leave a Comment