[swift-evolution] Immutable Structures
David Owens II
david at owensd.io
Wed Dec 23 12:01:07 CST 2015
I’m confused by your example below. Your move() function is equivalent to this:
func move(position: Position) {
var copy = position
copy.x += 20
}
Did you mean “var” there? (sidenote: var is being removed from the function call site)
Structs are immutable. It’s only with a var-declaration and a mutating function or it’s exposed properties, or the passing via inout, that structs appear to become immutable, but even that is a copy-on-write behavior. Like others have mentioned, the optimizer can remove this copy in many places for efficiency gains.
For instance, this is how you would change the incoming struct:
func move(inout position: Position) {
position.x += 20
}
var p1 = Position(x: 10, y: 10)
move(&p1)
This will print 30 both with struct or class.
> 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.
If you have a value-type type and it supports equality, then a struct is the “right” choice. That’s the basic guideline. So anything you wish to treat as a value and have value-semantics (which is basically copy-on-write), use a struct. That seems like what you are saying, and that’s already the case.
> 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.
Classes, by definition, remove value-semantics. I agree that this type of refactoring is inherently fragile, but I don’t see how having “immutable” structs changes this.
-David
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20151223/73540c60/attachment.html>
More information about the swift-evolution
mailing list