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

一个人想着一个人 提交于 2019-12-06 03:59:30

问题


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.


回答1:


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




回答2:


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.



来源:https://stackoverflow.com/questions/28263796/does-inout-var-parameter-make-any-difference-with-reference-type

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!