Swift 语言:如何用观察者定义计算变量?

Swift language: How to define a computed variable with observer?

我是 Swift 的新手,正在研究这门语言。我学习了计算变量变量观察者的概念。我想知道是否可以在定义变量时同时定义它们。我试过但失败了。下面是我的代码(不工作!)。

var a:Int = 88
{
    get
    {
        println("get...")
        return 77
    }

    set
    {
        a = newValue + 1
    }
}
{
    willSet
    {
        println("In willSet")
        println("Will set a to \(newValue)")
        println("Out willSet")
    }

    didSet
    {
        println("In didSet")
        println("Old value of a is \(oldValue)")
        println(a)
        if(a % 2 != 0)
        {
            a++
        }
        println("Out didSet")
    }
}

println(a)
a = 99

println(a)

我想知道,这可能吗?谢谢

我认为 属性 观察者只能应用于存储的属性。 计算属性和 属性 观察者的相似之处在于它们都在 属性 的值发生变化时被调用,我们甚至可以将计算属性视为 属性 观察者

所以,我认为我们不能用观察者定义计算变量。

简答,不可能。

我认为计算属性和存储属性的概念非常独特。

谈到存储属性,将其视为成员变量,具有知道何时设置或分配它们的功能。它们是存储的而不是计算的,因此可以为它们分配一个值,并且可以由其他 class 或定义 class 之外的方法设置或分配。

在计算属性的情况下,每次访问它们时都会计算它们,因此不会存储它们。我觉得即使设置的想法也不符合 Computed Properties 因为如果你设置它就不会计算。

对于 属性 中的 setter,您知道它何时被设置或分配,因此不需要 willSet 或 didSet。

var myProp: String {
    set {
        //You know it is being set here. :-)
        //No need of an event to tell you that!
    }
}

对于计算属性,观察者不会真正增加太多。像这样在 set 函数中做等价的事情很容易:

set {
    // do willSet logic here
    let oldValue = a

    a = newValue + 1

    // do didSet logic here
}

如果willSet或didSet逻辑复杂,可以重构为willSetA或didSetA等成员函数。

无法完成:

Welcome to Swift version 1.2. Type :help for assistance.
  1> class Foo { 
  2.     var bar : Int { 
  3.         get { return 1 } 
  4.         willSet { println ("will") }
  5.     } 
  6. }    
repl.swift:3:9: error: willSet variable may not also have a get specifier
        get { return 1 }
        ^

错误消息描述了原因。

Swift Language Guide已经明确表述如下...

"You don’t need to define property observers for nonoverridden computed properties, because you can observe and respond to changes to their value in the computed property’s setter. Property overriding is described in Overriding."

所以 "Set{ }" - setter 本身将充当观察者。