Protocols,willSet和didSet

时间:2015-12-12 17:30:57

标签: swift

class TriangleAndSquare {
    var triangle: EquilateralTriangle {
        willSet {
            square.sideLength = newValue.sideLength
        }
    }
    var square: Square {
        willSet {
            triangle.sideLength = newValue.sideLength
        }
    }
    init(size: Double, name: String) {
        square = Square(sideLength: size, name: name)
        triangle = EquilateralTriangle(sideLength: size, name: name)
    }
}
var triangleAndSquare = TriangleAndSquare(size: 10, name: "another test shape")
print(triangleAndSquare.square.sideLength)
print(triangleAndSquare.triangle.sideLength)
triangleAndSquare.square = Square(sideLength: 50, name: "larger square")
print(triangleAndSquare.triangle.sideLength)

swift中的协议就像Java中的接口一样?     任何人都可以解释一下上面例子中willSet和didSet到底是做什么的吗?

1 个答案:

答案 0 :(得分:2)

1。财产观察员

  • 当属性的值即将发生变化时,willSet中的代码会被调用。
  • 另一方面,当刚刚更改了属性的值时,将调用didSet

2。协议

如果协议对您有帮助,您可以将协议视为接口,但您可能希望watch the WWDC video "Protocol-oriented programming"查看协议在实践中的使用方式。