我知道有一些与此有关的问题.我知道
swift只能为计算属性定制属性setter和getter.但我认为这是
Swift最糟糕的部分.因为:
>所有变量都暴露在外面.没有私人或公共财产.
>无法访问属性的“内部”变量,如objective-c,_variable
我的代码是这样的:
- var value : Float = 0.0 {
- willSet {
- setValue(newValue,animated: false)
- }
- }
- func setValue(newValue:Float,animated:Bool) {
- if(newValue != self.value) {
- // TODO: this will cause problem because I there is no alternative way like Objective-c to access _value
- self.value = ....
- // do whatever I want
- }
- }
问题是在Objective-c中没有_value,self.value将导致值的willSet再次被调用.
任何的想法?谢谢
解决方法
willSet没有定义setter.集合.
- var privateValue: Float = 0.0;
- var value: Float {
- set(newValue) {
- if newValue != privateValue {
- privateValue = newValue;
- // do whatever I want
- }
- }
- get {
- return privateValue;
- }
- }
- All variables are exposed to outside. There is no private or public properties any more.
- There is no way to access the “internal” variable of the property like the objective-c,_variable
根据我的理解,privateValue将无法在本地范围之外的任何地方访问,这将解决您的两个投诉. (编辑:可访问性可能有误;请参阅注释.)