gpt4 book ai didi

swift - 为什么 '=' 赋值运算符在我的 didSet 属性观察器的 if 语句中不起作用?

转载 作者:行者123 更新时间:2023-11-28 10:50:54 25 4
gpt4 key购买 nike

struct Circle {
// Properties

var radius: Double {
didSet {
if oldValue < 0 {
radius = 0
}
}
}
var area:Double {
get{
return Double.pi * pow(radius, 2)
}
}
var circumference: Double {
get {
return 2 * radius * Double.pi
}
}
init() {
radius = 0
}
init(radius r: Double) {
radius = r
}

}

// test circle

var testCircle = Circle()
print ("radius:", testCircle.radius, "area: ", testCircle.area, "circumference: ", testCircle.circumference)

var testCircle2 = Circle(radius: 2.5)
print("radius: ", testCircle2.radius, " area: ", testCircle2.area, "circumference: ", testCircle2.circumference)

var testCircle3 = Circle(radius: 20)
print("radius: ", testCircle3.radius, "area: ", testCircle3.area, "circumference: ", testCircle3.circumference)

var testCircle4 = Circle(radius: -4.5)
print("radius: ", testCircle4.radius, "area: ", testCircle4.area, "circumference: ", testCircle4.circumference)

最佳答案

didSet 属性观察器不会在 init 期间被调用。您可以将赋值包装在 defer { ... } 语句中以强制调用 didSet

例如:

init(radius r: Double) {
defer { radius = r }
}

如果您希望默认半径为 0,我建议为 radius 使用默认参数值,如下所示:

init(radius r: Double = 0) {
defer { radius = r }
}

...这样您就可以避免使用两个 init 方法,并且仍然将 Circle 初始化为 Circle() (radius = 0) 并且作为 Circle(radius: 3) (radius = 3).

关于swift - 为什么 '=' 赋值运算符在我的 didSet 属性观察器的 if 语句中不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46124972/

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