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 }
*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)") }
Top comments (0)