Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Modifying an array passed as an argument to a function in Swift

Tags:

swift

Sorry for the newbie question; I'm still learning. I'm running into some odd behavior and couldn't find any documentation on this. I was wondering if you can help point out what I'm doing wrong here.

Error:

Cannot use mutating member on immutable value: 'arr' is a 'let' constant

class mySingleton {
    static let sharedInstance = mySingleton()
    private init() {}

    var men = ["bob", "doug"]
    var women = ["alice", "lisa"]

    func removeFirst() {
        self.arr.removeFirst()
    }

    func removeFirstByGender(gender: String) {
        if gender == "men" {
              self.modify(arr: self.men) // <-- error occurs here.
        } else {
              self.modify(arr: self.women) // <-- error occurs here.
        }
    }

    func modify(arr: [String]) {
        arr.removeFirst()
    }
}
like image 987
dmr07 Avatar asked Aug 11 '17 17:08

dmr07


People also ask

Can we pass an array as an argument to a function?

To pass an entire array to a function, only the name of the array is passed as an argument. result = calculateSum(num); However, notice the use of [] in the function definition. This informs the compiler that you are passing a one-dimensional array to the function.

What does actually passed when an array is passed as an argument to a function?

In case, when an array (variable) is passed as a function argument, it passes the base address of the array. The base address is the location of the first element of the array in the memory.

How do you change an array in Swift?

To replace an element with another value in Swift Array, get the index of the match of the required element to replace, and assign new value to the array using the subscript.

Are arrays passed by reference or value Swift?

Classes are passed by reference. Array and Dictionary in Swift are implemented as structs. Array is not copied / passed by value in Swift - it has very different behavior in Swift compared to regular struct.


1 Answers

You need to change the definition of modify to accept an inout parameter. By default, function arguments are immutable, but by using the inout keyword, you can make them mutable. You also need to pass the argument by reference.

func modify( arr: inout [String]) {
    arr.removeFirst()
}
var stringArr = ["a","b"]
modify(arr: &stringArr) //stringArr = ["b"] after the function call
like image 126
Dávid Pásztor Avatar answered Nov 01 '22 11:11

Dávid Pásztor