ios - Swift setter 和 getter 问题

标签 ios swift

<分区>

我知道已经有一些关于此的问题。而且我知道 swift 只能为计算属性自定义属性 setter 和 getter。但我认为这是 Swift 最糟糕的部分。因为:

  1. 所有变量都暴露在外。不再有私有(private)或公共(public)属性(property)。
  2. 无法像 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。 set 是。

var privateValue: Float = 0.0;
var value: Float {
  set(newValue) {
    if newValue != privateValue {
      privateValue = newValue;
      // do whatever I want
    }
  }
  get {
    return privateValue;
  }
}
  1. All variables are exposed to outside. There is no private or public properties any more.
  2. There is no way to access the "internal" variable of the property like the objective-c, _variable

据我了解,privateValue 将无法在本地范围之外的任何地方访问,这将解决您的两个投诉。 (编辑:可访问性可能有误;请参阅评论。)

关于ios - Swift setter 和 getter 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24623780/

相关文章:

ios - 等待请求完成后再执行下一步操作

ios - 在代码中使两个 AutoLayout 约束相等?

ios - 点击另一个 UITextField 后自动禁用键盘

swift - 如何以编程方式将 UILabel 和 UIImageView 添加到 CollectionView 中?

swift - Parse.com PFGeoPoint.geoPointForCurrentLocationInBackground 没有做任何事情

ios - 有没有办法以编程方式发送消息,而无需用户点击屏幕确认发送消息,而只是使用语音命令?

Swift 在十进制格式中失去精度

ios - Google驱动器无法通过iOS应用中的UIDocumentPickerViewController提供UTI

swift - 在 Swift 中使用 %@ 格式化字符串

ios - 导航栏项目不可见