In Swift can we change values of local parameters of function with in the function?
func exampleFunction(value : String, index : Int) -> Bool
value = "Changed Value" // it showing error
index = 3 // it showing error
var flag = exampleFunction("Passed Value" , 2)
var temp = value
temp = "temp Change"
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
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:
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
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.
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.