inout parameter swift – Beginner guide

By default parameters in swift function are constant. It means you can not change parameters values from inside of the function in swift. Sometimes we need to get parameters value to be modified from inside the function. So here, inout parameters comes to rescue as inout parameter in swift act like a reference type. Have a look at below code block

func swapTwoNumbers(_ numA:Int, _ numbB:Int) {
        let temporaryValue = numA
        numA = numbB
        numbB = temporaryValue

In above function named swapTwoNumbers, we are swapping the numbers passed as a parameters to the function. If you run the above code, compiler will throw an error “Cannont assign to value: ‘numA’ is a ‘let’constant”. Because parameters passed in a swift function are constant by default.

Cannont assign to value:  'numA' is a 'let'constant" - inout parameter swift

Using inout parameter

So here, to remove the above error we can use inout keyword and make these parameters as inout parameter in swift. Let us see how we can do it

 func swapTowNumbers(_ numA: inout Int, _ numbB:inout Int) {
        let temporaryValue = numA
        numA = numbB
        numbB = temporaryValue

Call a function using inout parameters

Function using inout parameters are called like any other normal function call. The only difference is, we need to add ‘&’ before the inout parameter name or value. ‘&’ signifies that we this parameter is an inout parameter. Secondly, the values we will pass as parameter should be a ‘Var’ i.e. variable value not a ‘let’ i.e. a constant value.

    	var firstNumber = 10
        var secondNumber = 30
        swapTowNumbers(&firstNumber, &secondNumber)
        print("Firstnumber == \(firstNumber), and secondnumber == \(secondNumber)")

If you run above code you can see, that both the numbers, firstNumber and secondNumbers are swapped and result is printed on xcode console.

Read more articles

Internet connectivity in iOS – How to check
Add multiple targets to swift project

%d bloggers like this: