Created
October 27, 2014 23:49
-
-
Save jochasinga/4b89721e380eac059b96 to your computer and use it in GitHub Desktop.
willSet hook in Swift
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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