Cristian
Cristian

Reputation: 117

Protocols, willSet and didSet

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

Answers (1)

TwoStraws
TwoStraws

Reputation: 13127

1. Property Observers

  • Code in willSet gets called when the value of a property is about to change.
  • On the other hand didSet gets called when the value of a property has just been changed.

2. Protocols

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

Related Questions