Swift - Function In-Out Parameters


By default, the function makes a copy of the variable and all changes are made to the copy.

When passing value types (such as Int , Double , Float , struct , and String ) into a function, the function makes a copy of the variables.

When passing an instance of a reference type (such as classes), the function references the original instance of the type and does not make a copy.

To make a function to change the value of a variable after it has returned, use the in-out parameter.

A parameter that persists the changes made within the function is known as an in-out parameter.

The following shows an example of an in-out parameter:

func fullName ( inout  name:String, withTitle title:String)  {
    name = title + " " + name;

Here, the name parameter is prefixed with the inout keyword.

This keyword specifies that changes made to the name parameter will be persisted after the function has returned.

To see how this works, consider the following code snippet:

var myName = "hi"
fullName(&myName, withTitle:"Mr.")
print(myName)  //prints out "Mr. hi"

Here, the original value of myName was "hi ". However, after the function has returned, its value has changed to "Mr. hi ".

You need to pass a variable to an inout parameter; constants are not allowed.

You need to prefix the & character before the variable that is passed into an inout parameter to indicate that its value can be changed by the function.

In-out parameters cannot have default values.

In-out parameters cannot be marked with the var or let keyword.

Related Topic