【问题标题】:Is it possible to pass attributes of a class as parameters? (SWIFT)是否可以将类的属性作为参数传递? (迅速)
【发布时间】:2017-08-01 06:28:40
【问题描述】:

所以...我的意思是:

class Test {
var a: String?
var b: String?
}

是否可以有一个基于参数更新 a 或 b 的函数?

有点像

func updateTest(_ attribute: Test.attribute,_ updateTo: String){

attribute = updateTo
}

然后像这样调用:

var test = Test()
updateTest(test.b, "foo")
print(test.b) // foo

【问题讨论】:

    标签: swift


    【解决方案1】:

    是的,您可以使用inout parameter:

    func updateTest(_ attribute: inout String?, _ updateTo: String) {
        attribute = updateTo
    }
    

    然后:

    updateTest(&test.b, "foo")
    

    这里&的含义见What does an ampersand (&) mean in the Swift language?。

    【讨论】:

    • 感谢元组!帮了大忙
    【解决方案2】:

    不,你不能那样做。但你可以这样做

    func updateTest(_ testClass: Test,_ updateTo: String){
        testClass.b = updateTo
    }
    

    所以你的代码是

    var test = Test()
    updateTest(test, "foo")
    print(test.b) // foo
    

    【讨论】:

      猜你喜欢
      • 2010-10-08
      • 1970-01-01
      • 1970-01-01
      • 2013-03-03
      • 1970-01-01
      • 2015-10-07
      • 1970-01-01
      • 2014-04-15
      相关资源
      最近更新 更多