11

Sorry for the newbie question; I'm still learning. I'm running into some odd behavior and couldn't find any documentation on this. I was wondering if you can help point out what I'm doing wrong here.

Error:

Cannot use mutating member on immutable value: 'arr' is a 'let' constant

class mySingleton {
    static let sharedInstance = mySingleton()
    private init() {}

    var men = ["bob", "doug"]
    var women = ["alice", "lisa"]

    func removeFirst() {
        self.arr.removeFirst()
    }

    func removeFirstByGender(gender: String) {
        if gender == "men" {
              self.modify(arr: self.men) // <-- error occurs here.
        } else {
              self.modify(arr: self.women) // <-- error occurs here.
        }
    }

    func modify(arr: [String]) {
        arr.removeFirst()
    }
}
8
  • 3
    See: stackoverflow.com/questions/24250938/… Commented Aug 11, 2017 at 17:30
  • Please edit your question to clearly indicate which line of code is causing the error. Commented Aug 11, 2017 at 17:34
  • 2
    This is an example quite far away from reality because you can access the arr property directly. Commented Aug 11, 2017 at 17:37
  • I would first make one of the arr-arrays an NSArray or rename it to prevent confusion. Then, I guess, the problem is that you can also call class properties without self.property. That means that maybe your function uses the classes arr, not the one in the arguments. Commented Aug 11, 2017 at 17:43
  • @vadian my use-case is when I have multiple arrays in a class, and I want a generic function to modify a select array. Commented Aug 11, 2017 at 18:00

1 Answer 1

13

You need to change the definition of modify to accept an inout parameter. By default, function arguments are immutable, but by using the inout keyword, you can make them mutable. You also need to pass the argument by reference.

func modify( arr: inout [String]) {
    arr.removeFirst()
}
var stringArr = ["a","b"]
modify(arr: &stringArr) //stringArr = ["b"] after the function call
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.