微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

swift – 覆盖didSet

我想覆盖属性观察者并调用“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.

@H_502_22@

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐