有没有办法将 willSet 参数添加到结构的实例变量?

Is there a way to add willSet parameter to a struct's instance variable?

我正在尝试按照这些思路做一些事情:

class MyCGPoint: CGPoint {
    override public x: CGFloat {
        willSet {
            
        }
    }
}

当然,我发现 类 不能扩展 Structs,所以我不确定如何将 willSet 方法附​​加到 CGPoint

中已经存在的 x 变量

我愿意接受这种方法的替代方法。我尝试这样做的原因是我可以在 willSet 方法中添加一个断点,并确定是什么导致我的 SKSpriteNode 位置发生变化(即使物理体速度为 0)

请参阅 SKPhysicsBody moving even when velocity is 0 了解我尝试使用此技术诊断的问题。

您不需要子类化结构(Swift 不允许您这样做)。只需创建您自己的具有相同签名的 Point,以及一种从您的 Point 转换为 CGPoint 的方法。然后用新的 Point

替换您实现中的 CGPoint
struct MyPoint {
  var x: CGFloat {
    willSet {
    
    }
  }
  var y: CGFloat

  var cgPoint: CGPoint { CGPoint(x: x, y: y) }
}

因为你需要这个来调试你可以 use a watchpoint-[SKSpriteNode setPosition:] 上的符号断点(虽然我没有测试这个)或者甚至是 SKSpriteNode 上的扩展像这样:

extension SKSpriteNode {
    open override var position: CGPoint {
        willSet {
            print("Position of \(self) will change to: \(newValue)")
            // Breakpoint here
        }
    }
}