加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

Swift引用属性并传递它

发布时间:2020-12-14 04:26:38 所属栏目:百科 来源:网络整理
导读:如何将属性引用分配给变量并传递给它.类似于函数的东西,我们可以做这样的事情: class Foo { func executeTask() { print("executeTask called") } var name: String = "name1"}// get reference to the executeTask methodlet x = Foo.executeTask// later
如何将属性引用分配给变量并传递给它.类似于函数的东西,我们可以做这样的事情:

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

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

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

// later we can call name property but using the y variable
y(Foo())()

但这会给出错误:实例成员’name’不能用于’Foo’类型

编辑:
大家好,问题绝不是要访问实例变量的属性来获取其当前值.这是一个微不足道的问题.
再看一下executeTask示例. executeTask定义为func executeTask()示例中的x是对函数的引用.我想要一个非常类似的东西来获取属性,我可以稍后调用以获取属性的值,请不要告诉我使用Container类.

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

解决方法

KeyPath可能不是您所要求的,但可能足够接近:

let y = Foo.name
let z = Foo()
z[keyPath: y]

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读