Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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 
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
268 views
Welcome To Ask or Share your Answers For Others

1 Answer

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 ef?cient 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!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...