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"]
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With