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’类型 编辑: 编辑2: 解决方法
KeyPath可能不是您所要求的,但可能足够接近:
let y = Foo.name let z = Foo() z[keyPath: y] 有关更多信息,请参阅:https://developer.apple.com/documentation/swift/keypath (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |