Properties 闭包的计算性质
我想使用闭包作为计算属性。我是说下面的代码Properties 闭包的计算性质,properties,swift,closures,Properties,Swift,Closures,我想使用闭包作为计算属性。我是说下面的代码 class MyClass { typealias myFuncType = () -> (Void) private var _myAction:myFuncType var myAction:myFuncType = { set(newAction){ self._myAction = newAction } } } 编译器是否有可能或会认为,当我打开一个带括号的文件时,
class MyClass {
typealias myFuncType = () -> (Void)
private var _myAction:myFuncType
var myAction:myFuncType = {
set(newAction){
self._myAction = newAction
}
}
}
编译器是否有可能或会认为,当我打开一个带括号的文件时,它一定是闭包定义?闭包(和函数)在swift中被宣传为一级公民,因此您可以像任何其他数据类型一样将它们存储在变量和属性中
也就是说,您的代码几乎很好,只需删除“=”,否则它将被视为具有内联初始化的存储属性。正确的代码是:
var myAction:myFuncType {
set(newAction) {
self._myAction = newAction
}
get { // see notes below
return _myAction
}
}
一些注意事项:
- 无需使用存储属性支持的计算属性-您的代码相当于:
class MyClass { typealias myFuncType = () -> (Void) var myAction: myFuncType }
- 如果在设置属性时需要进行其他处理,请使用:
和willSet
didSet
- 在计算属性中,如果实现setter,还必须提供getter