timman
timman

Reputation: 489

Cannot use mutating member on immutable value: Error in Swift

I created a short program to experiment with removing an element from an array by its value, rather than by index. I then want to print the updated list having removed this element.

However, I'm getting an error: 'Cannot use mutating member on immutable value: 'list' is a 'let' constant'. Why is list a constant value? Not sure if this is relevant, but I declared the array quarantineStuff as a variable. Why would list take a constant by default?

var quarantineStuff: [String] = ["zero to one book", "proper twelve whiskey", "coffee", "tonic water", "toilet roll", "broken electronics"]

func removeItemsICantTakeWithMe(list: [String]) -> [String] {
    if let index = list.firstIndex(of: "toilet roll") {
        list.remove(at: index)
    }
    return list
}

let renewedList = removeItemsICantTakeWithMe(list: quarantineStuff)
print(renewedList)

Upvotes: 1

Views: 5297

Answers (2)

Arpit Singh
Arpit Singh

Reputation: 58

var quarantineStuff: [String] = ["zero to one book", "proper twelve whiskey", 
"coffee", "tonic water", "toilet roll", "broken electronics"]

func removeItemsICantTakeWithMe(list: [String]) -> [String] {
    var aList = list // method object is immutable so we have to make a mutable object         

    if let index = aList.firstIndex(of: "toilet roll") {
        aList.remove(at: index)
    }
    return aList
}

let renewedList = removeItemsICantTakeWithMe(list: quarantineStuff)
print(renewedList)

Upvotes: 3

Gereon
Gereon

Reputation: 17844

All parameters in Swift are implicitly let / constants.

If you need to modify a parameter, you need to make it a var explicitly in your code:

func removeItemsICantTakeWithMe(list: [String]) -> [String] {
    var list = list // insert this line
    if let index = list.firstIndex(of: "toilet roll") {
        list.remove(at: index)
    }
    return list
}

Alternatively, you can use inout parameters to achieve a similar effect.

Upvotes: 5

Related Questions