← back to the blog

# Square Area and Circle Area in Swift 5 and Swift 5.1

##### Posted on November 23rd, 2019 by George

Examples on how to create a class Shape and then subclasses Square and Circle and how to use methods inheritance.

The examples contain methods to calculate the area for a Square and a Circle.

``````import Cocoa

class ShapeRdp {
var numberOfSides:Int = 0;
var id:Int64
var optionalDescription:String
var name:String

init(optionalDesc:String, name: String)  {
self.id = Int64(Date().timeIntervalSince1970 * 1000)
self.optionalDescription = optionalDesc;
self.name = name;
}

func simpleDescription() -> String {
return "A shape with so many sides: \(numberOfSides)";
}

func setSides(numberOfSides: Int)  {
self.numberOfSides = numberOfSides;
}
}

class Square:ShapeRdp {
var sidelength:Double

init(sideLength:Double, name:String) {
self.sidelength = sideLength;
super.init(optionalDesc: "Square",  name: name);
}

func area() -> Double {
return sidelength * sidelength;
}
}

class Circle:ShapeRdp {
var pi:Double = 3.14;
init(radius: Double, name: String) {
super.init(optionalDesc: "Circle", name: name);
}

func calcArea() -> Double {
return pow(radius,2) * pi;
}
}

let myShape = Square(sideLength: 24.55 ,name: "Nina");
myShape.setSides(numberOfSides: 4);
print(myShape.numberOfSides);

let myCircle = Circle(radius: 0.5, name: "Kyrill");

print(myCircle.calcArea())
print(myCircle.simpleDescription())
``````

Thank you.