本文介绍了属性观察者 willSet 和 didSet;属性 getter 和 setter的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

willSet - didSetget - set 有什么区别,在里面使用这个属性?

What is the difference between willSet - didSet, and get - set, when working with this inside a property?

在我看来,它们都可以为属性设置值.何时以及为什么应该使用 willSet - didSet,以及何时使用 get - set?

From my point of view, both of them can set a value for a property. When, and why, should I use willSet - didSet, and when get - set?

我知道对于 willSetdidSet,结构如下所示:

I know that for willSet and didSet, the structure looks like this:

var variable1 : Int = 0 {
    didSet {
        println (variable1)
    }
    willSet(newValue) {
    ..
    }
}

var variable2: Int {
    get {
        return variable2
    }
    set (newValue){
    }
}

推荐答案

  • willSet 在值被存储之前被调用.
  • didSet 在存储新值后立即调用.
    • willSet is called just before the value is stored.
    • didSet is called immediately after the new value is stored.
    • 考虑您的输出示例:

      var variable1 : Int = 0 {
              didSet{
                  print("didSet called")
              }
              willSet(newValue){
                  print("willSet called")
              }
          }
      
          print("we are going to add 3")
      
           variable1 = 3
      
          print("we added 3")
      

      输出:

      we are going to add 3
      willSet called
      didSet called
      we added 3
      

      它像前置/后置条件

      另一方面,如果你想添加一个只读属性,你可以使用get:

      On the other hand, you can use get if you want to add, for example, a read-only property:

      var value : Int {
       get {
          return 34
       }
      }
      
      print(value)
      
      value = 2 // error: cannot assign to a get-only property 'value'
      

      这篇关于属性观察者 willSet 和 didSet;属性 getter 和 setter的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-14 08:11