-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 
2
  • 5
    possible duplicate of How do you create an immutable array in Swift? Commented Jun 18, 2014 at 17:54
  • because the subscript for Array() is a nonmutating function. Commented Jun 18, 2014 at 18:34

2 Answers 2

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!

Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.