Swift: Virtual base class and polymorphism


(0 comments)

The protocol in Swift is similar to the virtual base class in C ++ except that it not only requires the classes using the protocol to implement the declared methods, the protocol also adds requirements that the classes must conform to.

In the program below both Triangle and Square classes use the Shape protocol

protocol Shape {
    var numberOfSides: Int { get }
    func display()
}

class Triangle: Shape {
    var numberOfSides: Int = 3
    func display() {
        print("A triangle has \(numberOfSides) sides")
    }
}

class Square: Shape {
    var numberOfSides: Int = 4
    func display() {
        print("A square has \(numberOfSides) sides")
    }
}

var shapes: [Shape] = []
shapes.append(Triangle())
shapes.append(Square())

for shape in shapes {
    shape.display()
}

The shapes array is an array of Shape protocols. But its elements can refer to objects of different classes that use the same Shape protocol. As a result, calling the display() method of the array's elements is transformed for each particular derived class

A triangle has 3 sides
A square has 4 sides

Currently unrated

Comments

There are currently no comments

New Comment

required

required (not published)

optional

required


What is 4 + 6?

required