swift - Immutable `var` array -


i'd create array in swift immutable, can replaced, in style of functional programming.

i understand can create them in way:

var mutable   = [1,2,3] // can change reference, add, remove, etc let immutable = [4,5,6] // cannot replace reference or add, remove, etc 

i want properties of immutability, still able change immutable array variable points to. example, fail:

myarr.append(42) // fails. immutable array 

but succeed:

// desired behavior: // multiply each element in immutable array 2 // return new immutable array, assigned old var immutable = immutable.map { $0 * 2 } // error: can't replace immutable ref 

similar, not answers:

what want doesn't make sense array, because value type value semantics. value of variable is array -- ability change variable , ability change array in way same thing.

semantically there no difference between:

myarr.append(42) 

and (made up):

myarr = myarr.newarraywithappending(42) 

in way, can imagine any "modification" value type variable implemented assigning new value variable. (it's not done way because inefficient, semantics point of view, there no reason why not implemented way.)


the concept of "mutability" makes sense reference types, variable reference points actual object, , actual object can shared between multiple references (so "mutation" through 1 reference can seen through one).

with reference types, can want, example immutable immutablearray class, , if have var variable of type immutablearray, can construct whole new immutable array , change variable point new array, particular array object cannot "changed" seen shared reference.


Comments

Popular posts from this blog

angularjs - ADAL JS Angular- WebAPI add a new role claim to the token -

php - CakePHP HttpSockets send array of paramms -

node.js - Using Node without global install -