5

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"]

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

2 Comments

So if it returns copy even if ill write: var temp =user.getList(); temp.append("bb") it doesn't modify original list, right?
@fessy, since Array is a struct and returned by value and not reference, it would be meaningless to allow you to modify it in the single statement, as the modified copy would be immediately discarded at the end of the statement (it would then have no remaining references) To make this point clearer, the compiler treats it as a "let" temporary. As Martin and Michael have both pointed out, the only way to modify the copy in the class is to access it directly, or via an append method on the class itself.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.