Swift "let" statement should define constant not mutable array

Originator:alexisgallagher
Number:rdar://17181951 Date Originated:2014-06-05
Status:Open Resolved:Unresolved
Product:iOS Product Version:8.0
Classification:serious bug Reproducible:always
 
/* 
Summary:
"let" is supposed to define constant values, but in fact it defines mutable, fixed-size arrays, as in C. This yields aliasing problems, allows functions to mutate their arguments (so you cannot know if they are pure functions), and plays havoc with clear reasoning.

"let"-defining an array should produce a truly constant value.

Instead, it now produces a constant reference to a mutable, fixed-size array.

This is just like C. So it is no better than C. And it's worth than 
Objective-C, where you could produce a reliably constant array with code like:

  NSArray * const ar = @[foo,bar,baz];

*/

import Cocoa

// 1. non-constant arrays produce unnecessary aliasing problems:

// w is a constant array
let w:Int[] = [10,10]
// v is a constant array
let v = [w,w]
v
// but I am plainly allowed to mutate their contents!
v[0][0]=20
// and I see the aliasing problems associated with mutability:
v

// 2. non-constant arrays undermine the purpose of the inout parameter

// this is a non-inout parameter, so this function should not mutate its arguments
func mutateFirstParam(arr:Int[]) -> () {
  arr[0] = 20
}
let Z:Int[] = [10,10]
Z
mutateFirstParam(Z)
Z // => Z has not been changed


// 3. non-constant arrays are inconsistent with Swift's constant dictionaries

// this dictionary is a variable, so I get to mutate it
var D = ["a":1]
D["a"]=2
D

// this dictionary is a constant, so I do not
let d = ["a":1, "b":2, "c":3]
d
d["a"] = 5  // this line produces an error, as it should

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!