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

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.


Hope you find this blog useful. Please feel free to contact with me in case you have any query, suggestions.  You can comment, like and follow posts.

You can request any topic related to Swift and iOS development.

Donate any small amount you think for this knowledge to grow this forum.                        

To Donate –