DEV Community

Cover image for inout parameters in Swift
NalineeR
NalineeR

Posted on

1

inout parameters in Swift

Inout parameters are the parameters which hold the reference to the original variable. Hence, any change in those params directly affects the original variable.

*How to accept inout param - * We need to add an additional keyword 'inout' just before the data type of parameter as below.

Below example is a function that swaps the values of the original variables.

func swapValues(x:inout Int,y:inout Int){
   let z = x
   x = y
   y = z
}
Enter fullscreen mode Exit fullscreen mode

*How to pass inout values - * While passing variable to inout type , we need to add the ampersand (&) with variable name. Check below -

override func viewDidLoad() {
   super.viewDidLoad()
   // Do any additional setup after loading the view.
   print("BeforeSwap-> a->\(a), b->\(b)")
   swapValues(x: &a, y: &b)
   print("AfterSwap-> a->\(a), b->\(b)")
}
Enter fullscreen mode Exit fullscreen mode

When you run this code you will see below output -
Image description

Do your career a big favor. Join DEV. (The website you're on right now)

It takes one minute, it's free, and is worth it for your career.

Get started

Community matters

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Dive into an ocean of knowledge with this thought-provoking post, revered deeply within the supportive DEV Community. Developers of all levels are welcome to join and enhance our collective intelligence.

Saying a simple "thank you" can brighten someone's day. Share your gratitude in the comments below!

On DEV, sharing ideas eases our path and fortifies our community connections. Found this helpful? Sending a quick thanks to the author can be profoundly valued.

Okay