An immutable value of type Array <String> has only a mutating member named 'append'

I have a simple case where I call some list and try to add a new value.

class User{ var list:Array<String> = [] func getList()->Array<String>{ return list } } var user = User() user.getList().append("aaa") // <-- ERROR user.list.append("aaa") // OK 

Immutable value of type Array<String> only has mutating member named 'append'

Why this does not work if user.getList() returns list .

I know there is no encapsulation in Java, but that seems weird.


[EDIT]

Regarding @MichaelDautermann answer:

 var user = User() // {["c"]} var temp:Array<String> = user.getList() // ["c"] temp += ["aaa"] // ["c", "aaa"] var z:Array<String> = user.getList() // ["c"] 
+5
source share
1 answer

The getList function returns an immutable copy of the list array , so you cannot change through the array retrieved using the getList() function.

But you can change the original array when accessing the member variable, as you found in your case, “ OK ”.

Basically, you probably need to add a “ list ” to the original array or write “ append ” for your class “ User ”.

+3
source

Source: https://habr.com/ru/post/1201996/


All Articles