Using in-out parameters in Swift functions

Divesh Singh
2 min readSep 18, 2019

--

In Swift all function parameters are constant by default, you can only read those parameters inside the functions. But can not modify

To modify those parameters inside the function you have to make it variable, and yes, Swift provides this, by using “inout” just before the type of parameters and after : .

In-out itself mean :

In : Allow modifying or allow inserting value

Out : Allow outing value or read value (This is default)

For example, if you want to change a number in the same memory location— i.e., change the value directly rather than returning a new one from functions

In the below example name and age value changing inside the function with the help of “inout”.

This is similar kind of passing object as a parameter and change the same object with the updated value.

The difference is : you always have to send reference of the type while calling function with parameter.

So the purpose of using “inout” is when you want to modify value in the same memory location you should use this otherwise use normal function parameter.

“inout” allow function to take a parameter as a reference.

You can explicitly define them as variables on the function definition:

Using in-out parameters

Thanks,

--

--

Divesh Singh
Divesh Singh

Written by Divesh Singh

Postgraduate from JEC Jabalpur || iOS and macOS developer, traveler |||| EM at Darwinbox | Ex-Samsung || Ex - Optimize IT Sys | Ex - R Systems

No responses yet