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

我只是一个虾纸丫 提交于 2019-12-04 08:15:32

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.

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