In-Out Parameters in iOS Swift

Function parameters are constants by default. Trying to change the value of a function parameter from within the body of that function results in a compile-time error. This means that you can’t change the value of a parameter by mistake. If you want a function to modify a parameter’s value, and you want those changes to persist after the function call has ended, define that parameter as an in-out parameter instead.

let us compare same function and without and with in-out parameter

Ex. 1

Without parameter

func swapTwoInts(_ a: Int, _ b: Int) {
let temporaryA = a
a = b
b = temporaryA
}

it will give following error because we can not change constant values, as function parameters are constants by default.

Screen Shot 2017-01-08 at 1.00.07 PM.png

With in-out parameter

 func swapTwoInts(_ a: inout Int, _ b: inout Int) {
    let temporaryA = a
    a = b
    b = temporaryA
}

var someInt = 3
var anotherInt = 107
swapTwoInts(&someInt, &anotherInt)

print("someInt is now (someInt), and anotherInt is now (anotherInt)")

swapTwoInts don’t have return value but it still modifies the values of someInt and anotherInt outside of function.

Ex. 2

We can pass outer variable as parameter in function and can change it’s value inside function

var greeting = "Hello"

func sayHello(greeting : inout String){
    
    greeting = "Sandesh"
}
print(greeting)  // Hello

sayHello(greeting: &greeting)

print(greeting)  // Sandesh

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s