-1

In swift a value in an immutable array can be changed but a value in an immutable dictionary can not be changed Why?

let imArray = ["Ram","Shyam","Bharat"] 
imArray[2] = "Abhimanyu" // this change will be apply though it is immutable 
Connor Pearson
  • 63,902
  • 28
  • 145
  • 142
  • 5
    possible duplicate of [How do you create an immutable array in Swift?](http://stackoverflow.com/questions/24090741/how-do-you-create-an-immutable-array-in-swift) – Tim Jun 18 '14 at 17:54
  • because the _subscript_ for `Array()` is a `nonmutating` function. – holex Jun 18 '14 at 18:34

2 Answers2

5

EDIT: In Xcode 6 beta 3 notes, this is now changed. They now behave the same.

Array in Swift has been completely redesigned to have full value semantics like Dictionary and String have always had in Swift.  This resolves various mutability problems – now a 'let' array is completely immutable, and a 'var' array is completely mutable – composes properly with Dictionary and String, and solves other deeper problems.  Value semantics may be surprising if you are used to NSArray or C arrays: a copy of the array now produces a full and independent copy of all of the elements using an efficient lazy copy implementation.  This is a major change for Array, and there are still some performance issues to be addressed.  Please see the Swift Programming Language for more information.  (17192555)


I talked to an Apple engineer regarding this in WWDC

For arrays, when you define it as a constant, this means the backing buffer is constant, and thus you can change the contents of the buffer, but not swap out the buffer or modify its length.

For dictionaries, it is completely immutable.

Of course, if you think it should behave differently, submit a ticket to them!

Jack
  • 16,677
  • 8
  • 47
  • 51
2

From Apple's Swift documentation, under Mutability of Collections...

Immutability has a slightly different meaning for arrays, however. You are still not allowed to perform any action that has the potential to change the size of an immutable array, but you are allowed to set a new value for an existing index in the array. This enables Swift’s Array type to provide optimal performance for array operations when the size of an array is fixed.

Dharmesh Vaghani
  • 718
  • 6
  • 23