In Swift, function arguments are constants by default. Attempting to change parameter values in the function body will result in a compilation error. This means you cannot change parameter values. If you want a function that can modify the values of its arguments, and you want those changes to persist after the function call ends, define the argument as inout.

var variable: Int = 1

func changeNumber(num: Int) {
    num = 2
    print(num)
}

changeNumber(num : variable)
Copy the code

Failed to compile:

We cannot modify the parameters of a function. But by defining input and output parameters through inout:

var variable: Int = 1

func changeNumber(num:inout Int) {
    num = 2
    print(num)
}

changeNumber(num: &variable) / / 2
Copy the code

When calling a function, we use the & that might give you the impression of passing references — especially if you have a C or C++ background. But the inout:

An inout parameter has a value that is passed in to the function, is modified by the function, and is passed back out of the function to replace the original value.

The use of & does pass the memory address of the argument to the function (the argument is passed by reference), but changeNumber does not manipulate the pointer internally. It copies In Copy Out:

  • When this function is called, the value of the argument is copied to produce a copy.
  • The memory address of the copy is passed to the function (the copy is passed by reference), and the value of the copy can be modified inside the function
  • After the function returns, the value of the copy overwrites the value of the argument.

For a more detailed discussion of inout, see

  • in-out-parameters
  • Swift Series ten – The essence of Inout

conclusion

Inout is a frequently used keyword in Swift, so much so that we have to write an independent article to emphasize its copy-in copy-out, in case of stereotyped thinking caused by experience.

Understand code better and write better code.

Refer to the

  • In-Out Parameters
  • ‘inout in Swift
  • About the inout
  • swift – When to use inout parameters?
  • Compile in-depth analysis of the nature of Inout