Skip to content

Instantly share code, notes, and snippets.

@ronaldmannak
Last active August 29, 2015 14:02
Show Gist options
  • Save ronaldmannak/4b8c1e7c03c7cffe238e to your computer and use it in GitHub Desktop.
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.…
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
@ronaldmannak
Copy link
Author

@willem That is correct, any function that changes the number of items in a string and unshare() create a copy of the array.

@ronaldmannak
Copy link
Author

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.

@artm
Copy link

artm commented Jun 7, 2014

This looks like:

  1. constants are copied by reference - logical since they aren't supposed to change
  2. variable arrays are copied by value, could be lived with once realized
  3. === compares object identity
  4. "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