0

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.

7
  • 1
    But Array is not a class, is a struct... Commented Mar 29, 2018 at 5:25
  • 1
    If you add object in array then it should be mutable to do so . If you created array with let then it is constant just for reading purpose after assignment. it is normal behaviour in any programming language Commented Mar 29, 2018 at 5:25
  • side note: you can just a user a where clause on the for loop: for number in numbers where threshold < number { result.append(number) } Commented Mar 29, 2018 at 5:55
  • Further side note, you can just use filter: return numbers.filter { threshold < $0 } Commented Mar 29, 2018 at 5:56
  • @PrashantTukadiya Actually, most of the popular languages have arrays with reference semantics. For example, readonly and final (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. Commented Mar 29, 2018 at 5:58

1 Answer 1

2

In Swift Array is a struct which is value type. To change in the properties of struct you need to make both object and properties var type.

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

Comments

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.