Functions-Constant and Variable as Parameters in Swift

Function parameters are constants by default. Trying to change the value of a function parameter from within the body of that function results in a compile-time error. This means that you can’t change the value of a parameter by mistake. For example:

Here s1 s2 and joiner are Constants by default. by constants I mean; they will only take a value and not a variable holding a value in the function call. The function call for the above defined function is as follows.

Here all parameter variables take in values which are constants. S1 takes a string Hello, S2 takes World, Joiner takes a character ‘-‘. All these values are constants as they don’t change. But not always will the parameter s1 s2 and joiner will have hello, world and – as its values. Thus the need  for excepting variables as parameter value comes into existence.

Swift provides this functionality by prefixing the parameter name with the keyword ‘var'

the following is the function call.

  •  The changes you make to a variable parameter do not persist beyond the end of each call to the function, and are not visible outside the function’s body. The variable parameter only exists for the lifetime of that function call.

In-Out Parameters:

If you want a function to modify a parameter’s value, and you want those changes to persist after the function call has ended, define that parameter as an in-out parameter instead.

You can only pass a variable as the argument for an in-out parameter. You cannot pass a constant or a literal value as the argument, because constants and literals cannot be modified. You place an ampersand (&) directly before a variable’s name when you pass it as an argument to an inout parameter, to indicate that it can be modified by the function.

The swapTwoInts function simply swaps the value of b into a, and the value of a into b. The function performs this swap by storing the value of a in a temporary constant called temporaryA, assigning the value of b to a, and then assigning temporaryA to b. You can call the swapTwoInts function with two variables of type Int to swap their values. Note that the names of someInt and anotherInt are prefixed with an ampersand when they are passed to the swapTwoIntsfunction:

The example above shows that the original values of someInt and anotherInt are modified by theswapTwoInts function, even though they were originally defined outside of the function.

Next we will learn about different types in functions.