swiftswift-structs

Why doesn't didSet work?


In many examples of didSet I see on SO, this code will return 0, however, I can't get it to return anything other than the original value. What am I doing wrong?

Swift

struct Circle {
    var radius: Double {
        didSet {
            if radius < 0 {
                radius = 0
            }
        }
    }
}

var circ = Circle(radius: -25)

print(circ.radius)

Output

-25

Solution

  • didSet isn't called during initialization, only afterwards. If you want to validate data during initialization, your initializer should do it.

    If you add:

    circ.radius = -50
    print(circ.radius)
    

    you'll see it working as you'd expect, and the output will be 0.0.