Textlogo_codingem_white

Programming tips for everyone

Swift: What Is Inout?

As you might already know, changing the value of a parameter passed into a function is not possible, as they are constants.

For example, this code refuses to compile:

func change(_ number: Int) {
    number = 2
}

var number = 1
change(number)

However, sometimes it is really useful when you can directly change the parameter passed into a function. But how can you do it if it is not possible the way I did it above?

This is where inout parameters come in handy: An inout parameter can be modified inside a function and the changes apply outside the function.

For example:

func change(_ number: inout Int){
    number = 2
}
var number = 1
change(&number)
print(number)

Output:

2

Now if you examine the example a bit closer, please pay attention to these two things:

  • The number parameter is of type inout Int. This makes it possible to modify it inside the function.
  • When you call the change function, you need to use & in front of the variable name: change(&number). This indicates that the variable can be modified by the function.

Thanks for reading. I hope you enjoy it. Feel free to share it in order for others to find it too.

Share on facebook
Share on twitter
Share on linkedin

Related Articles

Artturi Jalli

Technical Writer

Entrepreneur, Software Engineer, Mobile App Dev, MSc Physics Student, And Tech Enthusiast from Finland

artturi@codingem.com

My Personal Favorites
Sponsor

Buy an Online Course

Lorem ipsum dolor sit amet consectetur adipiscing elit dolor
Explore Categories

Favorites