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

      

+3


source to share


2 answers


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



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

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

      

+4


source


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>

.

+1


source







All Articles