From: Matt Neuburg Book 'Fundamentals of iOS 13 Programming with Swift.' :
If we want the function to change the original value of the argument passed to it, we must do the following:
- The type of parameter that we are going to change must be declared inout .
- When we call the function, the variable containing the mutable value must be declared with var, not let.
- Instead of passing a variable as an argument, we should pass its address. This can be done by prepending an ampersand (& amp;) in front of its name.
Our removeCharacter (_: from :) method now looks like this:
func removeCharacter(_ c:Character, from s: inout String) -> Int { var howMany = 0 while let ix = s.firstIndex(of:c) { s.remove(at:ix) howMany += 1 } return howMany }
And our call to removeCharacter (_: from :) now looks like this: var s = "hi" let result = removeCharacter ("l", from: & s) After the call, the result is 2, and s is "heo". Note the ampersand before the name s when we pass it as an argument from::. Required; if you skip this, the compiler will stop you. I like this requirement because it forces us to explicitly admit to the compiler and ourselves that they were going to do something potentially dangerous: to allow this function, as a side effect, to change the value outside of itself.
source share