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到底是做什么的吗?
答案 0 :(得分:2)
willSet
中的代码会被调用。didSet
。如果协议对您有帮助,您可以将协议视为接口,但您可能希望watch the WWDC video "Protocol-oriented programming"查看协议在实践中的使用方式。