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()
}
}
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.
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.
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.
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.
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
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