Swift引用属性并传递它

moh*_*945 4 swift

如何将属性引用分配给变量并传递给它.类似于函数的东西,我们可以做这样的事情:

class Foo {

    func executeTask() {
        print("executeTask called")
    }

    var name: String = "name1"
}

// get reference to the executeTask method
let x = Foo.executeTask

// later we can call the executeTask method but using the x variable
x(Foo())()
Run Code Online (Sandbox Code Playgroud)

但我们怎样才能为物业做同样的事情.我原以为:

// get reference to the executeTask method
let y = Foo.name

// later we can call name property but using the y variable
y(Foo())()
Run Code Online (Sandbox Code Playgroud)

但是这给出了错误: instance member 'name' cannot be used on type 'Foo'

编辑:伙计们,问题绝不是要访问实例变量的属性以获取其当前值.这是一个微不足道的问题.再看一下这个executeTask例子.在executeTask被定义为func executeTask()SO x的中的示例是起作用的参考.我想要一个非常类似的东西来获取属性,我可以稍后调用以获取属性的值,请不要告诉我使用Container类.

编辑2:用更好的例子来解释.

vad*_*ian 5

一个函数可以用作闭包,属性不能.
一种解决方案是添加自定义函数来访问属性,没有直接的方法.

class Foo {

  var name: String = "name1"

  func getName() -> String {
    return name
  }
}

let y = Foo.getName
y( Foo() )()
Run Code Online (Sandbox Code Playgroud)


Tyl*_* A. 5

KeyPath 可能不完全符合您的要求,但可能足够接近:

let y = \Foo.name
let z = Foo()
z[keyPath: y]
Run Code Online (Sandbox Code Playgroud)

有关更多信息,请参阅:https://developer.apple.com/documentation/swift/keypath https://developer.apple.com/videos/play/wwdc2017/212/