Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does inout/var parameter make any difference with reference type?

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?

Code example:

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.

like image 350
Binarian Avatar asked Feb 01 '15 14:02

Binarian


2 Answers

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).

like image 200
Sergey Kalinichenko Avatar answered Sep 30 '22 13:09

Sergey Kalinichenko


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.

like image 25
newacct Avatar answered Sep 30 '22 13:09

newacct