C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Size: This modifies the inout parameter to equal 10. After size() returns, "x" still equals 10.
Swift program that uses inout parameter
func size(x: inout Int) {
// Set out parameter.
x = 10
}
// Value equals 0.
var x = 0
print(x)
// Call size with inout argument.
size(x: &x)
// Now variable equals 10.
print(x)
Output
0
10
X: In this example the x() func use an inout depth argument. When depth reaches 10, no more calls occur.
Tip: The memory location of the depth argument is shared among all calls of the "X" func.
Swift program that uses inout in recursive method
func x(depth: inout Int) {
// Increase depth value.
depth += 1
if (depth < 10) {
// Use recursion to increase depth again.
x(depth: &depth)
}
}
// Count depth of recursion.
var depth = 0
x(depth: &depth)
print(depth)
Output
10
Note: This makes sense. A constant cannot be modified—its memory location should not be available.
Swift program that causes inout argument error
func test(name: inout String) {
}
// Cannot use let keyword with inout.
let name = ""
test(name: &name)
Output
Cannot pass immutable value as inout argument:
'name' is a 'let' constant
Info: It is unclear which approach for multiple return values is best. Try them all and decide.
Quote: You can only pass a variable as the argument for an in-out parameter. You cannot pass a constant or a literal value as the argument, because constants and literals cannot be modified.
Swift Programming Language: apple.com