[swift-evolution] Immutable Structures

Douglas Gregor dgregor at apple.com
Wed Dec 23 15:57:08 CST 2015

> On Dec 23, 2015, at 7:44 AM, Lino Rosa via swift-evolution <swift-evolution at swift.org> wrote:
> I believe the language would be improved by making structures immutable.
> 1) The choice between classes and structures isn’t clear right now. If structures were immutable it would be natural to use them as value objects.
> 2) Refactoring a mutable structure into a class when it’s being passed around multiple threads removes the by-value semantics seamlessly. The resulting mutable class isn’t thread-safe.
> 2.1) Even when passed around a single thread, the resulting class would be passed by reference, so any mutations would have unintended consequences.
> 3) We could probably remove some syntax: `mutating` keyword and variable parameters. Also the `var` keyword before a structure could be used to denote reassignment (not mutability), just as it does with classes.
> Of corse I might not be seeing the whole picture, so please weigh in.

Swift’s structures, enums, and standard library collections provide value semantics, which is far more useful than true immutability because it gives you immutability guaranteed when you want them (“let”) and efficient local mutation when you need it (“var”) . If you haven’t seen the “Building Better Apps with Value Types in Swift” talk from WWDC 2015, I suggest you check it out to get a sense of how value types work in Swift:


We’re very happy with value semantics as a programming model, so the likelihood of moving to a model where a value of struct type is always immutable is effectively zero. My hope is that the talk above—or other resources about value semantics in Swift—will convince you as thoroughly as it convinced us ;)

	- Doug

More information about the swift-evolution mailing list