'How does Initialization and class inheritance of function work in Swift
Based on example from JavaScript code I would like to apply the same steps in Swift. If you can help me to understand how it can work to get area of all shapes.
Was trying to solve it with below code, however it does not work.
class Shape {
func getArea() {
}
}
class Square: Shape {
var a: Double
init(a: Double) {
self.a = a
super.init()
}
override func getArea() {
a * a
}
}
class Rectangle: Shape {
var a: Double
var b: Double
init(a: Double, b: Double) {
self.a = a
self.b = b
super.init()
}
override func getArea() {
a * b
}
}
class Circle: Shape {
var r: Double
init(r: Double) {
self.r = r
super.init()
}
override func getArea() {
r * r * Double.pi
}
}
let square = Square(a: 1.1)
let rectangle = Rectangle(a: 5.0, b: 9.1)
let circle = Circle(r: 2.3)
let shapes = [square, rectangle, circle]
func getTotalArea() -> Double {
let areas = shapes.map { $0.getArea() }
let sum = areas.reduce (1, +)
return sum
}
let shapesArea = getTotalArea()
print(shapesArea)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|

