Swift: Copying behavior of arrays is confusing
| Originator: | |||
| Number: | rdar://17265500 | Date Originated: | 2014-06-11 |
| Status: | Open | Resolved: | |
| Product: | Developer Tools | Product Version: | Xcode 6 beta 1 |
| Classification: | Usability | Reproducible: |
As documented in the Swift Programming Guide, Array is supposed to act like a value type, except when it doesn't. This adds a weird corner case to the language and will no doubt prove a source of all kinds of wonderful bugs.
Currently this is how it works:
let a = [1, 2, 3]
var b = a
b[1] = 5
a // [1, 5, 3]
b.append(4)
a // [1, 5, 3]
b // [1, 5, 3, 4]
The array is not copied unless its length changes.
This behavior also exists when the array is part of another value type:
struct Yummie {
var a = [1, 2, 3]
}
var x = Yummie()
var y = x
y.a[1] = 5
x.a // [1, 5, 3]
This behavior is really hard to reason about.
It is more reasonable to assume that doing var b = a makes a real copy. The unshare() function should not need to exist, and unsharing should happen automatically behind the scenes when an array is placed into a new variable.
The current behavior of Array seems to have been designed only with runtime efficiency in mind, not with how human beings think.
Comments
Please note: Reports posted here will not necessarily be seen by Apple. All problems should be submitted at bugreport.apple.com before they are posted here. Please only post information for Radars that you have filed yourself, and please do not include Apple confidential information in your posts. Thank you!