I get that let is used for constants and var is used for variables. However, this piece of code has confused me.
func filterGreaterThanValue(value: Int, numbers: [Int]) -> [Int] {
let result:[Int] = [Int]()
for number in numbers {
if number > value {
result.append(number)
}
}
return result
}
Running this yields the error
error: MyPlayground.playground:5:13: error: cannot use mutating member on immutable value: 'result' is a 'let' constant
result.append(number)
^~~~~~
To my understanding, an object declared with the let keyword is immutable in the sense that I can change its properties, but cannot reassign the variable pointing to that object to a different object (ie. have it point to another address in memory).
However, in this example I'm doing the same thing right? I've initialized an array object and I'm just modifying its properties. Why am I not allowed to do this?
Thanks.
Arrayis not a class, is a struct...whereclause on theforloop:for number in numbers where threshold < number { result.append(number) }filter:return numbers.filter { threshold < $0 }readonlyandfinal(in C# and Java, respectively) ensure that a reference is not mutated, but they have no say over what happens to the object the reference... references.