gpt4 book ai didi

swift - 覆盖 didSet

转载 作者:搜寻专家 更新时间:2023-10-30 22:34:25 24 4
gpt4 key购买 nike

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

最佳答案

我在 Playground 上试过你的代码,但出现错误

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"

这就是我在 consol 中得到的:

name has been set
print this first

关于swift - 覆盖 didSet,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35128118/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com