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)
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]
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With