Home > Software design >  How to fix "Cannot use mutating member on immutable value: 'cleanup' is a 'let&#
How to fix "Cannot use mutating member on immutable value: 'cleanup' is a 'let&#

Time:08-24

Here I am trying to add a user's username to the list of users in a Cleanup object. I tried adding inout, but it returns another error saying "cannot pass immutable value as inout argument: 'cleanup' is a 'let' constant" at where I call the function.

//this is the function

func joinCleanup(user: BBPBUser, cleanup: Cleanup){
  
    do {
        cleanup.users.append(user.username) //here is where the error occurs
        try db.collection("Cleanups").document(cleanup.username).updateData(["users" : cleanup.users])
        currCleanup = cleanup
    }
    catch {
        self.errorMessage = "Error joining cleanup."
    }
}

//this is where I call it (this is in a view)

let currCleanup: Cleanup?
let currUser: BBPBUser?


if let cleanup = self.currCleanup, let user = self.currUser {

        Button {
            cleanupsManager.joinCleanup(user: user, cleanup: cleanup)          
        }
}

CodePudding user response:

As mentioned by others, by default parameters are passed to functions as read-only let constants. You need to add the inout label to a parameter if you want to pass it by reference and be able to change its value in the called function:

func joinCleanup(user: BBPBUser, cleanup: inout Cleanup){
    // Your code here
}

Then when you call it you need to prefix the variable with an & to indicate that you are passing it by reference:

var aCleanup = Cleanuup() // Replace with your code to create a `Cleanup` obj. This must be a `var`, not a `let` constant.

joinCleanup(user: aUser, cleanup: &aCleanup) // Note the `&`
  • Related