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
Can't see mail in Inbox? Check your Spam folder.
Comments
LbsxPhing 3 weeks, 3 days ago
online discount pharmacy <a href="https://ssviagriia.com/ ">viagra 100 mg price</a> pharmacy online
Link | ReplyNew Comment