Reputation: 117
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)
Protocols in swift are like interfaces in Java? Can anyone explain me what exactly do willSet and didSet in example above?
Upvotes: 2
Views: 1080
Reputation: 13127
willSet
gets called when the value of a property is about to change.didSet
gets called when the value of a property has just been changed.You can think of protocols as being like interfaces if it helps you, but you might want to watch the WWDC video "Protocol-oriented programming" to see how protocols are being used in practice.
Upvotes: 3