Suppose I have the following class:
class Some {
var list = [String]()
}
// In other places, I want to append to the list
someInstance.list.append("new string")
// ...but I do not want to re-assign the list itself:
someInstance.list = [String]()
What is the exact syntax for declaring list
?
There's no syntax that does exactly what you're asking for, because Array
is a value type, and so modifying the whole value and appending to the elements are both the same kind of modification. (With a reference type, replacing the reference and appending to the array are semantically different things.)
The simplest way to do this is to:
-
Make the property privately settable:
private(set) var list = [String]()
-
Add a function on the
Some
type to append elements:
func appendList(_ newElement: String) {
list.append(newElement)
}
...
someInstance.appendList("new string")
This is the easiest approach if the number of ways of modifying the array are very limited. If you want to provide a lot of other mutating functions, then more complex approaches are possible.