Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to fix 'can not use mutating member on immutable value'? [closed]

Tags:

swift

Getting the error:

Error : cannot use mutating member on immutable value : 'fromArray' is a 'let' constant

In the following code:

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 is here
        }
    }
    return fromArray
}

var anarray : [Int] = [1, 2,3, 4 ,3]
var x = 3
removing(item: x, fromArray: anarray)
like image 929
Nahid Raihan Avatar asked Mar 01 '17 19:03

Nahid Raihan


3 Answers

Parameters in swift is constant by default, but if you want to mutate it in the function then it needs to be in place inout variable. You can achieve it by specifying the parameter as inout as follows

func removing (item: Int, fromArray : inout [Int]) -> [Int]
like image 109
ldindu Avatar answered Sep 27 '22 21:09

ldindu


Well, you also have a problem of removing elements from the array and then going beyond its bounds. Try it like this:

func removeInPlace(item: Int, fromArray: inout [Int]) -> Void {

    for i in stride(from: fromArray.count - 1, to: 0, by: -1)
    {
        if fromArray[i] == item {
            fromArray.remove(at: i)
        }
    }

}

var anarray : [Int] = [1, 2,3, 4 ,3]

var x = 3

print(anarray)    // prints [1, 2, 3, 4, 3]

removeInPlace(item: x, fromArray: &anarray)

print(anarray)    // prints [1, 2, 4]

You'll want additional error handling, but hope this helps get you on your way.

like image 36
DonMag Avatar answered Sep 27 '22 21:09

DonMag


If you want to modify a method parameter inside the method, you can declare it using the inout keyword (see the docs):

func removing(item: Int, fromArray: inout [Int]) -> [Int]
{
    ...
}

Without the inout keyword, all method parameters are constant values.

like image 29
Ted Hopp Avatar answered Sep 27 '22 21:09

Ted Hopp