覆盖didSet

时间:2016-02-01 10:24:43

标签: swift properties

我想覆盖属性观察者并调用" super.didSet"。这可能吗?

class Foo {
    var name: String = "" { didSet { print("name has been set") } }
}

class Bar: Foo {
    override var name: String = "" { 
        didSet { 
            print("print this first")
            // print the line set in the superclass
        }
    }
}

1 个答案:

答案 0 :(得分:7)

我在游乐场尝试了你的代码并得到了错误

  

使用getter / setter的变量不能具有初始值。

所以我刚刚从orverriding变量中删除了=""。如下所示:

class Foo {
    var name: String = "" { didSet { print("name has been set") } }
}

class Bar: Foo {
    override var name: String  {
        didSet {
            print("print this first")
            // print the line set in the superclass
        }
    }
}

let bar = Bar()
bar.name = "name"

这就是我在consol中得到的:

name has been set
print this first