Skip to content

Instantly share code, notes, and snippets.

@jochasinga
Created October 27, 2014 23:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jochasinga/4b89721e380eac059b96 to your computer and use it in GitHub Desktop.
Save jochasinga/4b89721e380eac059b96 to your computer and use it in GitHub Desktop.
willSet hook in Swift
class Circle {
var radius: Double
init(radius: Double) {
self.radius = radius
}
}
class Square {
var sideLength: Double
var numSides: Int
init(sideLength: Double) {
self.sideLength = sideLength
numSides = 4
}
}
class CircleAndSquare {
var circle: Circle {
willSet {
square.sideLength = newValue.radius
}
}
var square: Square {
willSet {
circle.radius = newValue.sideLength
}
}
init(length: Double) {
circle = Circle(theRadius length: length)
square = Square(sideLength: length)
}
}
var circleAndSquare = CircleAndSquare(length: 10)
circleAndSquare.circle.radius // 10
circleAndSquare.square.sideLength // 10
circleAndSquare.square.sideLength = 20 // Set the square's sideLength to 20
circleAndSquare.circle.radius // 20
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment