Mohit Jethwa Mohit Jethwa - 14 days ago 11
Swift Question

How can we change Function Parameter?

In Swift can we change values of local parameters of function with in the function?

Like:

func exampleFunction(value : String, index : Int) -> Bool
{
value = "Changed Value" // it showing error
index = 3 // it showing error
return true
}


Calling function in viewDidLoad():

var flag = exampleFunction("Passed Value" , 2)


Is this possible to change value and index in exampleFunction scope? if not than is there any other way to do this? Because Using this we only change value of temp.

var temp = value
temp = "temp Change"

Answer

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, inout index: 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.