简体   繁体   中英

computed property value not updated

I defined a computed property num in my ViewController :

class ViewController: UIViewController {
   var myArr:[Int]{
      get {
        return [1,2,3]
      }
   } 

   var num: Int{
       get {
         return myArr.count
       }
       set {}
   }

   fun updateState() {
      num--
      // why num is 3 here? why not 2?
      print(num)
   }

   ...
}

when I call updateState() function, it first num-- , then print out num , but it gives 3 not 2. Why?

num will always be 3 because it is a computed property whose value is taken from the length of the literal array. The only way to change num In your current code is to change the size of myArray .

The get method of a computed property is used to determine its value, not just its initial value, so num-- is effectively meaningless in this context.

So based on your requirement that num is initially the size of the array but can then be modified, you will need a stored property to track the current value and a setter method:

class ViewController: UIViewController {
   var trackingNum:Int?
   var myArr:[Int]{
      get {
        return [1,2,3]
      }
   } 

   var num: Int{
       get {
         if self.trackingNum == nil {
             self.trackingNum=self.myArr.count
         }
         return self.trackingNum
       }
       set {
           self.trackingNum=newValue
       }
   }

   func updateState() {
      num--
      print(num)
   }

   ...
}

You can make your num property lazy to make it have an initial value of your array's count and still be able to decrement it like you are expecting.

lazy var num: Int = { [unowned self] in
    return self.myArr.count
}()

It will have an initial value of whatever the count is of your array during the first time you reference num

You haven't implemented the setter. Therefore num always returns the count of the array. Which is always 3.

class C {
    var myArr:[Int]{
        get {
            return [1,2,3]
        }
    }

    lazy var num: Int = self.myArr.count
    func updateState() {
        num--
        print(num)
    }
}

let c = C()
c.updateState()
c.updateState()
c.updateState()
// ... prints
/*
2
1
0
*/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM