enum ShapeDimensions {
// point has no associated value - it is dimensionless
case point
// square's associated value is the length of one side
case square(side: Double)
// rectangle's associated value defines its width and height
case rectangle(width: Double, height: Double)
func area() -> Double {
switch self {
case .point:
return 0
case let .square(side: side):
return side * side
case let .rectangle(width: w, height: h):
return w * h
}
}
func perimeter() -> Double {
switch self {
case .point:
return 0
case let .square(side: side):
return side * 4
case let .rectangle(width: w, height: h):
return (w * 2) + (h * 2)
}
}
}
let squareShape = ShapeDimensions.square(side: 10.0)
let rectangleShape = ShapeDimensions.rectangle(width: 5.0, height: 10.0)
let pointShape = ShapeDimensions.point
print("square's perimeter = \(squareShape.perimeter())")
print("rectangle's perimeter = \(rectangleShape.perimeter())")
print("point's perimeter = \(pointShape.perimeter())")
Edit: Forgot to include the ShapeDimensions declarations.