Mutate function parameters in Swift

It seems from your example that you need to change the passed arguments inside the function as a side effect, and need the updated values to be available after the function call. If that's the case, you need to use the inout modifier.

Otherwise, if all you need is to modify the parameters inside of the function call, you can explicitly define them as variables on the function definition:

Using in-out parameters

First, change your function declaration to:

func exampleFunction(inout value: String, index: inout Int) -> Bool

Now, an in-out parameter has a value that is passed in to the function, is modified by the function, and then is passed back out of the function, replacing the original value. For this to work, you can't pass a literal into your function, since there would be nowhere to store the modified value afterwards. In fact, it has to be a variable. You cannot pass a constant or a literal value as the argument, because constants can't be modified. Hence, change your function call to:

var passed = "passedValue"
var index = 2

var b = exampleFunction(&passed, &index)

After the call, both passed and index will contain the new values, as modified by the function.

Also, note the & before each argument when calling the function. It must be there, to indicate the argument can be modified by the function.

Using variable parameters – Removed in Swift 3

In this case, all you need to do is change your function declaration to use variable parameters, as below:

func exampleFunction(var value: String, var index: Int) -> Bool

Changes made to the arguments inside the scope of the function, aren't visible outside the function or stored anywhere after the function call.


If it's just for the function scope, you can declare your function as

func exampleFunction(var value : String, var index : Int) -> Bool { }

Note - However that was removed in Swift3.

Simply add a var ..

func exampleFunction(value : String, index : Int) -> Bool {
      var value = value
      var index = index

indeed, the Xcode IDE will autofix that for you.


If your intention is to modify the parameters in their global context, you can use inout.


var Parameter is deprecated and will be removed from Swift 3.0. If you want to change the parameter inside your function body you should store the passed parameter in some local variable and change it

    func exampleFunction(var value: String, var index: Int) -> Bool {
       var index = index
       ...
    }

inout Parameter is still there though. So if you want that the changes that you make to the passed parameter should be reflected outside the function body, you should be using inout Parameter.

Tags:

Swift