Swift In-Out parameters

Siddharth Paneri
2 min readMay 7, 2019

When I first encountered inout parameters, I did not think it would be as easy as breathing air (like you do it and you don’t even notice it.)

You can place inout just before argument type in a function and you have implemented it, let’s understand some basics and why we use inout. finally will see a working example.

Background of swift functions

We know Swift functions are easy to write and call, but there is one more thing to it, every argument that we pass through a swift functions tends to be a constant. I can prove it to you. just try to modify an argument inside the function body and you will get a compile time error!

You are guessing it right in-out parameters have an impact outside the scope of the function and can be used to modify the variables which are passed in as arguments to the function.

Syntax

inout keyword is placed just before we specify the type of the argument.

When we call this function we will use ampersand & before the variable that we pass in as an argument (will se an example shortly)

Limitations

Yes there are some limitations to inout parameters

  1. Constants/literals cannot be passed in inout parameters
  2. inout parameters cannot have default value
  3. variadic parameters cannot be marked as inout.

Where to use?

Many of us have this question in mind before we actually start using this in out code. Where should we use this? What is the requirement of inout if we can create functions that returns some values?

Trust me, during development we come across a lot of scenarios where we need to modify the variables and that too at a lot of places and one of the reason of creating functions is that, we do not end up writing redundant code.

So what if we need to write a code to swap two integers

We will come up with something like above, but consider one thing if we need to use this code a some other places as well, what will we do. We create function.

How to use?

As I said above. To avoid redundancy in our code we can create functions. And to create a function with inout params solve our problem of swapping two integers and using the code widely.

--

--

Siddharth Paneri

iOS Applications expert with strong skills in design, architecture, UX standards, and DevOps for Mobile. Product ideology!