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]
IMHO the simplest workaround is simply wrap it in the closure as follows:
let mutableElements = [0,1,2,3]
let reallyImmutable = {[0,1,2,3]}
println(mutableElements)
for i in 0..mutableElements.count { mutableElements[i] *= -1 }
println(mutableElements) // [0, -1, -2, -3]
println(reallyImmutable())
for i in 0..reallyImmutable().count { reallyImmutable()[i] *= -1 }
println(reallyImmutable()) // [0, 1, 2, 3]
println(reallyImmutable()[2]) // 2
let anotherImmutable = { reallyImmutable().map{ $0 * $0 } }
println(anotherImmutable()) // [0, 1, 4, 9]
You pay extra {} on declaration and () for each access but that also makes your code speak for itself.
Dan the Mutable Programmer
P.S. Wrote a wrapper class ImmutableArray.