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)

最佳答案

didSetinit期间不调用属性观察器。您可以将赋值包装在defer { ... }语句中,以强制调用didSet
例如:

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

如果希望默认半径为0,我建议使用radius的默认参数值,如下所示:
init(radius r: Double = 0) {
    defer { radius = r }
}

…这样就避免了使用两个init方法,并且仍然将aCircle初始化为Circle()radius = 0)和Circle(radius: 3)radius = 3)。

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

10-10 10:57