Question about Property Observer

I'm studying swift to develop macOS app so far.

I wrote a following code to learn property observer.

    var x:Int
    var y:Int
    
    var oppositePos:coordinatePoint{
        get{
            coordinatePoint(x: -x, y: -y)
        }
        set{
            x = -newValue.x
            y = -newValue.y
        }
    }
}

I want to implement property observer on opposites property so I changed code as follows :

    var x:Int
    var y:Int
   var oppositePos:coordinatePoint {
        willSet{
            print("\(oppositePos) is changed to \(newValue)")
        }
        didSet{
            print("\(oldValue) is changed to \(oppositePos)")
        }
    }
}

after changing code, I ran it but I got following error messages:

  1. Value type 'coordinatePoint' cannot have a stored property that recursively contains it
  2. Missing argument for parameter 'oppositePos' in call

My question: property observer is available on this property? if so, what should I change in this code?

if someone give me an advice to fix errors, I'd be very appreciate.

thanks,

c00012

Based on the first error message you listed, it seems like you actually had this:

struct oppositePoint {
    var x:Int
    var y:Int
    
    var oppositePos:coordinatePoint{
        get{
            coordinatePoint(x: -x, y: -y)
        }
        set{
            x = -newValue.x
            y = -newValue.y
        }
    }}

which is fine, but then you changed it to this:

struct oppositePoint {
    var x:Int
    var y:Int
   var oppositePos:coordinatePoint {
        willSet{
            print("\(oppositePos) is changed to \(newValue)")
        }
        didSet{
            print("\(oldValue) is changed to \(oppositePos)")
        }
    }}

That doesn't work because now oppositePos is a stored property of type coordinatePoint inside the declaration of coordinatePoint, which is recursive and can't be resolved by the Swift compiler.

What do you actually mean by "property observer"? Are you interested in accessors such as didSet and willSet, or in something based on the new @Observable macro, or one of the other forms of observation available in OS frameworks?

Note that when you define struct or class, as coordinatePoint, it should start with Uppercase, CoordinatePoint.

First, I'm sorry for not expressing my question clearly.

I'd like to ask if I can implement property observer on "oppositePos" computed property to monitor change of opposite point according to change of original coordinatePoint.
However, on my second thought, I realized I couldn't implement it on the property and I didn't need to do it.

anyway, I got my answer for the question thanks to your advice.

again, thanks for your advice .

c00012

Question about Property Observer
 
 
Q