inout/var参数与引用类型有什么区别吗? [英] Does inout/var parameter make any difference with reference type?

查看:148
本文介绍了inout/var参数与引用类型有什么区别吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道inout值类型的作用.

对于对象或任何其他引用类型,在那种情况下该关键字是否有目的,而不是使用var?

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

它可能与参数列表中的var关键字相同.

It could be the same as simply the var keyword in the parameter list.

推荐答案

区别在于,当您将按引用参数作为var传递时,您可以自由更改所有可以更改的内容 inside 传递的对象,但是您无法将对象更改为完全不同的对象.

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)

在这里,testInoutParameterObject中的代码将一个全新的MyClass对象设置为传递给它的testClass变量.用Objective-C术语来说,这大致相当于将指针传递到指针(两个星号)与传递指针(一个星号).

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

这篇关于inout/var参数与引用类型有什么区别吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆