Saturday, November 26, 2022
HomeiOS Developmentinout parameter swift – Newbie information – iOSTutorialJunction

inout parameter swift – Newbie information – iOSTutorialJunction


By default parameters in swift perform are fixed. It means you can’t change parameters values from inside the perform in swift. Generally we have to get parameters worth to be modified from contained in the perform. So right here, inout parameters involves rescue as inout parameter in swift act like a reference sort. Take a look at beneath code block

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

In above perform named swapTwoNumbers, we’re swapping the numbers handed as a parameters to the perform. In case you run the above code, compiler will throw an error “Cannont assign to worth: ‘numA’ is a ‘let’fixed”. As a result of parameters handed in a swift perform are fixed by default.

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

Utilizing inout parameter

So right here, to take away the above error we will use inout key phrase and make these parameters as inout parameter in swift. Allow us to see how we will do it

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

Name a perform utilizing inout parameters

Perform utilizing inout parameters are referred to as like every other regular perform name. The one distinction is, we have to add ‘&’ earlier than the inout parameter title or worth. ‘&’ signifies that we this parameter is an inout parameter. Secondly, the values we’ll go as parameter must be a ‘Var’ i.e. variable worth not a ‘let’ i.e. a relentless worth.

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

In case you run above code you possibly can see, that each the numbers, firstNumber and secondNumbers are swapped and result’s printed on xcode console.

Learn extra articles

Web connectivity in iOS – Learn how to test
Add a number of targets to swift venture

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments