Swift – In Out Parameters
In Swift, a function is a collection of statements clubbed together to perform a specific task. A function may or may not contain a return type. The return type of the function decides the type of value returned by a function. For example, if we want to return an integer value from a function then the return type of the function has to be Int, if we want to return a decimal value from a function then the return of the function has to be Float or Double etc. We can declare a function in Swift with the help of “func” keyword. The general syntax of a function in Swift is given below,
func myFunction(parameters (optional) ) -> returnType (optional)
The function also contains parameters. A parameter is a variable that is defined during a function declaration or definition. By default, parameters passed to a function in Swift are constant parameters. By constant we mean, the value represented by them cannot be changed. If you try to change then the compiler will give error.
func myFunction(num1: Int, num2: Int)
Here, num1 and num2 are the parameters of the function. So to modify the value of the parameters use in-out parameters. So in this article, we fupon in-out parameters used in Swift.
In out parameters:
Suppose, we have a function that accepts a number of parameters and we want to make changes in the values of those parameters. Moreover, these changes must be reflected outside the function as well. In such scenarios, We can use in-out parameters. It means we pass the parameters value in the function and passed back out of the function to replace the original value of the parameters. In-out parameters follow the same syntax as we have seen above in the section except we have to explicitly specify “inout” keyword just before the data type and while calling the function we have to use an ampersand(&) before the parameters. Ampersand(&) explicitly tells the compiler that we want to modify these values inside the function. Another reason for using Ampersand (&) is that we want to use an alias for the existing parameters rather than making copies.
func myFunction(num1: inout Int, num2: inout Int)
In the below program, we are swapping two integer numbers using a third variable by specifying in-out parameters. Here, num1 and num2 are declared as in-out so we can modify them.
Before swapping: num1 is 10 and num2 is 20 After swapping: num1 is 20 and num2 is 10
In the below program we are swapping two strings using a third variable by specifying in-out parameters. Here, string1 and string2 are declared as in-out so we can modify them.
Before swapping: string1 is GeeksforGeeks and string2 is Geeks After swapping: string1 is Geeks and string2 is GeeksforGeeks