Swift - pass structure to method?
The following code gives a compilation error because it assumes that the array that was passed to the function is no longer modified. I know that Array is a structure and therefore is passed by value instead of a reference, so how do you deal with something like this when you pass a structure to a method and want to change it? Don't use the extension in this case.
var array = ["1", "2", "3"]
array.removeLast()
removeOne(array)
func removeOne(array: Array<AnyObject>) {
array.removeLast()
}
source to share
You can use the in-out parameter to do this:
func removeOne(inout array: Array<String>) {
array.removeLast()
}
var array = ["1", "2", "3"]
array.removeLast()
removeOne(&array)
Also note that I changed Array<AnyObject>
to Array<String>
as the compiler will figure out var array = ["1", "2", "3"]
how Array<String>
and won't be able to apply it to Array<AnyObject>
.
source to share