Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
275 views
in Technique[技术] by (71.8m points)

Why in immutable array in swift value can be changed?

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

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

1 Reply

0 votes
by (71.8m points)

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!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...