Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

swift

I have simple case where I call some list and try to append 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 It doesn't work if user.getList() returns list.

I know there is no encapsulation like in Java but it seems strange.


[EDIT]

Regards to @MichaelDautermann answer:

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

var z:Array<String> = user.getList()     // ["c"]
like image 909
snaggs Avatar asked Oct 21 '22 02:10

snaggs


1 Answers

Your "getList" function is returning an immutable copy of the list array, which is why you can't modify via an array retrieved via the getList() function.

But you can modify the original array when you access the member variable, as you've discovered in your "OK" case.

Basically you'll probably either need to append on the original "list" array, or write an "append" func for your "User" class.

like image 141
Michael Dautermann Avatar answered Oct 23 '22 23:10

Michael Dautermann