I know what inout
does for value types.
With objects or any other reference type, is there a purpose for that keyword in that case, instead of using var
?
private class MyClass {
private var testInt = 1
}
private func testParameterObject(var testClass: MyClass) {
testClass.testInt++
}
private var testClass: MyClass = MyClass()
testParameterObject(testClass)
testClass.testInt // output ~> 2
private func testInoutParameterObject(inout testClass: MyClass) {
testClass.testInt++
}
testClass.testInt = 1
testInoutParameterObject(&testClass) // what happens here?
testClass.testInt // output ~> 2
It could be the same as simply the var
keyword in the parameter list.
The difference is that when you pass a by-reference parameter as a var
, you are free to change everything that can be changed inside the passed object, but you have no way of changing the object for an entirely different one.
Here is a code example illustrating this:
class MyClass {
private var testInt : Int
init(x : Int) {
testInt = x
}
}
func testInoutParameterObject(inout testClass: MyClass) {
testClass = MyClass(x:123)
}
var testClass = MyClass(x:321)
println(testClass.testInt)
testInoutParameterObject(&testClass)
println(testClass.testInt)
Here, the code inside testInoutParameterObject
sets an entirely new MyClass
object into the testClass
variable that is passed to it. In Objective-C terms this loosely corresponds to passing a pointer to a pointer (two asterisks) vs. passing a pointer (one asterisk).
It does the exact same thing for all types. Without inout
, it is pass-by-value (regardless of type). That means assigning (=
) to the parameter inside the function has no effect on the calling scope. With inout
, it is pass-by-reference (regardless of type). That means assigning (=
) to the parameter inside the function has the same effect as assigning to the passed variable in the calling scope.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With