Last active
August 29, 2015 14:02
-
-
Save ronaldmannak/4b8c1e7c03c7cffe238e to your computer and use it in GitHub Desktop.
Behold the Quantum-Array: Arrays in Swift seem to be behaving like a struct and object, depending on the operation performed on the array. Open this gist in a playground. See https://twitter.com/ronaldmannak/status/474706423310340096 Update 6/6/2014: made example easier to read, removed irrelevant code, and added response from an Apple engineer.…
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
let anArray = [1, 2, 3] // A constant array | |
let anotherArray = anArray // make anotherArray point to anArray | |
anArray === anotherArray // true. anArray points to anotherArray | |
// Let's try the same with a variable array | |
var aMutableArray = [4, 5, 6] | |
var anotherMutableArray = aMutableArray // Should work like constant arrays, but... | |
anotherMutableArray === aMutableArray // Surprise: this returns false | |
// Update: According to an Apple engineer, this is a compiler bug. | |
// The value should return true, both arrays should point to the same variable array | |
aMutableArray[0] = 99 | |
anotherMutableArray // [99, 5, 6] | |
aMutableArray // [99, 5, 6] Both arrays show the 99 as first item, suggesting the === above is indeed a bug | |
aMutableArray.append(7) // By appending an item to a variable array, the array gets copied implicitly | |
// .unshare() also copies the array implicitly | |
aMutableArray // [99, 5, 6, 7] | |
anotherMutableArray // [5, 6, 7] still points to the original array |
This looks like:
- constants are copied by reference - logical since they aren't supposed to change
- variable arrays are copied by value, could be lived with once realized
===
compares object identity- "constantness of an array" refers to the array's own fields (length, pointer to the data buffer), but not to the contents of the buffer - the least useful property. My mental model would be - a "constant array" is a buffer to which many references are possible, while the variable array is an actual collection object.
How is passing various arrays to functions work though?
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Just be aware that changing values within an array (which, surprisingly is also possible to do with constant arrays, defined with 'let') does not copy the array.