Swift array and dictionary immutability -



Swift array and dictionary immutability -

what intended design of swift's 'immutable arrays' allow update operation. whereas, 'immutable dictionaries' lone exempted particular behavior. thoughts...

let newarray = ["1","3","4"] // immutable <string> array 'newarray' newarray[1]="2"//update index 1 value 2 (no error) newarray[2]="3"//update index 2 value 3 (no error) allow newdictionary = [1 : "one", 2 : "third"]//immutable <int,string> dictionary 'newdictionary' newdictionary[2] = "second" // update 2 keyed value "third" (throws error)

why immutable arrays lone allowing update operation, why immutable dictionary not allowed update operation.

in documentation it's been written, optimal performance sake, specify fixed sized arrays immutable(constant) arrays. optimal things performed on immutable arrays. thoughts....

dictionary , array re-create value when utilize it

from swift book

array:

“for arrays, copying takes place when perform action has potential modify length of array. ”

so long dont alter size of array, constant variable still utilize same size , our constant still point @ old value.

dictionary:

“whenever assign dictionary instance constant or variable, or pass dictionary instance argument function or method call, dictionary copied @ point assignment or phone call takes place.”

so dictionary, every time it, re-create , assign variable. breaks rule of let

this prove of dictionary copying

class test { var newdictionary: dictionary<int,string> = [:] { didset { println("reset") } } func test() { newdictionary = [1 : "one", 2 : "third"] newdictionary[2] = "second" } } test().test()

output is

reset reset

edit: array phone call didset when update value. cannot prove happen inside, apple knows

arrays dictionary swift

Comments

Popular posts from this blog

php - Android app custom user registration and login with cookie using facebook sdk -

django - Access session in user model .save() -

php - .htaccess Multiple Rewrite Rules / Prioritizing -