How do I create an immutable array in Swift?
A superficial reading of the docs would suggest you can just do
let myArray = [1,2,3]
But sadly this actually produces a mutable, fixed-size array. This mutability creates the usual puzzles with unsuspected aliasing and functions mutating their arguments:
let outterArray = [myArray, myArray]
outterArray[0][0] = 2000
outterArray //=> [[2000,2,3],[2000,2,3]] surprise!
func notReallyPure(arr:Int[]) -> () { arr[0] = 3000 }
notReallyPure(myArray)
myArray // => [3000,2,3]
Not much better than C.
If I want immutability, is the best option really to wrap it in an NSArray
like so:
let immutableArray = NSArray(myArray: [1,2,3])
That seems nuts. What am I missing here?
UPDATE (2015-07-26):
This question dates from the very early days of Swift. Swift has since then been updated so that immutable arrays are actually immutable, as answers below indicate.