Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift - pass struct to a method?

Tags:

swift

The following code gives a compile error because it thinks the array that was passed to the function is not mutable anymore. I know that Array is a struct and therefore passed by value instead of reference, so how do you deal with something similar to this where you pass a struct to a method and you want to be able to modify it? Don't want to use an extension in this case.

var array = ["1", "2", "3"]
array.removeLast()
removeOne(array)

func removeOne(array: Array<AnyObject>) {
   array.removeLast()
}
like image 353
aryaxt Avatar asked May 14 '26 23:05

aryaxt


1 Answers

@Mike S's answer above is correct, but if you want to use this for any type you'll need a generic function:

func removeOne<T>(inout array: Array<T>) {
    array.removeLast()
}

var array = ["1", "2", "3"]
removeOne(&array)
like image 169
Nate Cook Avatar answered May 18 '26 16:05

Nate Cook



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!