Reputation: 12446
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.
Upvotes: 8
Views: 1771
Reputation: 122439
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.
Upvotes: 4
Reputation: 726579
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).
Upvotes: 11