Posts for Tag: immutable

Swift Arrays - Beta 3 (Hooray!)

I should probably have written this sooner as it has been 10 days since Beta 3 was released, but I've only just noticed that there is a bit of traffic still coming in about Swift Arrays from my earlier posts about the array semantics in the first Swift betas. The short version is that I'm very happy with the new Swift Arrays in Beta 3 which have full value semantics (optimised with copy on write under the hood). The syntax for declaring arrays has also changed which is fine although I didn't have a particular problem with the old syntax. Be sure to update the Swift iBooks (delete and download again) as there are some significant changes.

The copy() and unshare() functions are gone because unshare has essentially become the default behaviour (although contents changes not just length changes now trigger the copy so copy is not needed either).

Semantic Changes

  1. Arrays are no longer reference types. You can treat every assignment, argument pass and function return as if it were a copy.
  2. Changing the contents of an array is no longer permitted when the array is declared constant with let.

In this example you can see the copy-on-write (CoW) behaviour using the identity operator (=== which I wouldn't recommend you doing in real code to affect behaviour on the CoW status but it enables us to observe the CoW). In the example it doesn't make any difference if a is declared with let or var but b must be declared as var otherwise you will get a compile time error because the contents change.