The Swift 3 Programming Language – Init, Deinit, Subclassing & overriding

Init, Deinit, Subclassing & overriding


Use init to create an initializer to setup the class when an instance is created.


Use deinit to perform some cleanup before the object is deallocated.


Subclasses include their super-class name after their class name, spearated by a colon.


Subclass can override methods of super class by marking methods with override in sub-class.

Example 1: Init example

// A class declaration with `init` example
class NamedShape {
    // a property declaration
    var numberOfSides = 0

    // a property to store name of shape
    var name: String

    // Example of initializer
    init(name: String) { = name

    // a method declaration
    func simpleDescription() -> String {
        return "A shape with \(numberOfSides) sides."

Example 2: Subclassing, deinig & overriding

// Example of sub-classing
class Square: NamedShape {

    // it's own property other than super-class
    var sideLength: Double

    // `init` for initializing an instance
    init(sideLength: Double, name: String) {
        self.sideLength = sideLength
        super.init(name: name)
        self.numberOfSides = 4

    // it's own method other than super class
    func area() -> Double {
        return self.sideLength * self.sideLength

    // Example of overriding super class methods
    override func simpleDescription() -> String {
        return "A square with sides of length \(sideLength)"

    // Example of deinitializer
    deinit {
        self.sideLength = 0
        self.numberOfSides = 0 = ""

// creating an object of class Square
let test = Square(sideLength: 10.15, name: "My Example Square")

// Printing area
print("Area of test square is \(test.area())")

// printing description of shape

Output of above code is as follows.

Area of test square is 103.0225
A square with sides of length 10.15

Click here to open actual swift-playground file for above illustration