nahid Raihan nahid Raihan -4 years ago 157
Swift Question

'can not use mutating member on immutable value ' how to fix this error in my code below?

func removing (item: Int, fromArray: [Int]) -> [Int]

{

for i in 0...fromArray.count-1
{
if fromArray[i] == item {
let index = i
fromArray.remove(at: index) // Error : cannot use mutating member on immutable value : 'fromArray' is a 'let' constant

}
}
return fromArray
}

var anarray : [Int] = [1, 2,3, 4 ,3]
var x = 3
removing(item: x, fromArray: anarray)

Answer Source

The error you are seeing is due to trying to remove an array value from an array that is read-only. That is, fromArray is read-only and thus immutable. You have two options.

Option #1: Make the input array read-write by adding an inout to it, and passing back nothing:

func removing (item: Int, fromArray: inout [Int]) {

    for i in 0...fromArray.count-1 {
        if fromArray[i] == item {
            let index = i
            fromArray.remove(at: index) // Error : cannot use mutating member on immutable value : 'fromArray' is a 'let' constant
        }
    }
}

Option #2: Use the function as is, but copying the array into a new one:

func removing (item: Int, fromArray: inout [Int]) {

    var newArray = fromArray
    for i in 0...newArray.count-1 {
        if newArray[i] == item {
            let index = i
            newArray.remove(at: index) 
        }
    }
    return newArray
}

Unless indicated by inout, any parameter passed to a function in Swift is always read-only.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download