Swift Function – Pass Parameter by Reference

To pass parameter by reference to a Swift function, define this parameter with inout keyword, and use preface the parameter in function call with ampersand (&).

The syntax to pass parameter by reference to a function in Swift is

func functionName(parameterName: inout Type) {
    //body
}

var param: Type = initialValue
functionName(&param)

Example

In the following program, we define a function incrementByN() where the parameter x is defined as inout. When we call this function, we pass the variable someNumber by reference using ampersand.

main.swift

func incrementByN(x: inout Int, n: Int = 0) {
    x = x + n
}

var someNumber = 10
print("someNumber before function call : \(someNumber)")
incrementByN(x: &someNumber, n: 7)
print("someNumber after  function call : \(someNumber)")

Output

Swift Function - Pass Parameter by Reference
ADVERTISEMENT

Conclusion

In this Swift Tutorial, we learned how to pass parameter by reference to a function.