[Swift] Constant Arrays should be immutable

Originator:amolloy
Number:rdar://17301730 Date Originated:6/13/14
Status:Closed Resolved:Duplicate of 17192555
Product:Developer Tools Product Version:
Classification: Reproducible:
 
In Swift, the "let" keyword creates a new constant, immutable variable. This works as expected in the general case, including with Swift Dictionary objects. However, an Array object defined in this way does not follow this contract, and is in fact mutable. While the Array's length is fixed, its members can be changed. This behavior is inconsistent with the rest of the language, can provide surprising results, and is in general Not A Good Idea. A constant Array should be truly immutable.

There has been some discussion in the developer community, including conjecture that Array behaves the way it does in order to provide a fast, C-like array. This may or may not be the case, but either way the idea of having fast C-like arrays in Swift is appealing. It would be safer and more sensible, though, for that to be its own type, completely separate from Array, something like FixedArray. This separation would force programmers to consider their situation and only use the less safe mutable fixed length array where it really makes sense to, while allowing them to use the safer truly immutable array everywhere else.

Steps to Reproduce

Create a new Playground in Xcode 6.
Enter the following:
let someArray = [0, 1, 2]
someArray[0] = 3

Or use the attached playground.

Expected Results

someArray is constant, so the compiler should emit an error when writing to index 0 in the second line of code.

Actual Results

someArray[0] takes the value 3.

Configuration

Xcode Version

Additional Notes

Comments


Please note: Reports posted here will not necessarily be seen by Apple. All problems should be submitted at bugreport.apple.com before they are posted here. Please only post information for Radars that you have filed yourself, and please do not include Apple confidential information in your posts. Thank you!