DEV Community

Cover image for inout parameters in Swift

Posted on

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() {
   // 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

Top comments (0)