当前位置 : 主页 > 手机开发 > 其它 >

swift – 覆盖didSet

来源:互联网 收集:自由互联 发布时间:2021-06-11
我想覆盖属性观察者并调用“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
我想覆盖属性观察者并调用“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
        }
    }
}
我已经在游乐场尝试了你的代码并得到了错误

Variable with getter/ setter cannot have and initial value.

所以我只是从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"

这就是我在康复中所得到的:

name has been set
print this first
网友评论