Skip to content

Polymorphism

  • Lesson
  • 2 min read
  • 3 of 6 in this chapter

Parent-Child Relationship

Classes can inherit from each other (HistoryBook inherits from Book), where HistoryBook gets all its base info from Book. HistoryBook is the same as Book, except with some added extras. Below is an example of some classes.

Swift
class Dessert {
var price: Int
 
 init(price: Int) {
 self.price = price
 }
}
 
class IceCream: Dessert {
 var flavor: String
 
 init(price: Int, flavor: String) {
 self.flavor = flavor
 super.init(price:price)
 }
}
 
class Cake: Dessert {
 var filling: String
 
 init(price: Int, filling: String) {
 self.filling = filling
 super.init(price: price)
 }
}

In this code, we created a parent class called Dessert, with the price property. We created two children: IceCream and Cake. They both had new properties, flavor and filling, respectively.

Using Polymorphism

This is the whole deal behind polymorphism. We can create new code with this term. We can create new objects from the child classes, but they all still classify as part of the parent class as well!

Swift
var mintChocolateChip = IceCream(price: 4, flavor:"Mint Chocolate Chip")
var upsideDownCake = Cake(price: 14, flavor:"Pineapple Upside Down")
var blackForestCake = Cake(price: 18, flavor:"Black Forest")
 
var desserts: [Dessert] = [mintChocolateChip, upsideDownCake, blackForestCake]

We put all of these variables in the same array, because they all come from the same parent class, Dessert.

Adding a method

Now, let’s add a taste() method.

Swift
class Dessert {
 var price: Int
 
 init(price: Int) {
 self.price = price
 }
 func taste() -> String {
 return ("This desert tastes good.")
 }
}
 
class IceCream: Dessert {
 var flavor: String
 
 init(price: Int, flavor: String) {
 self.flavor = flavor
 super.init(price:price)
 }
 override func taste() -> String {
 return ("This \(flavor) Ice Cream is the best!")
 }
}
 
class Cake: Dessert {
 var filling: String
 
 init(price: Int, filling: String) {
 self.filling = filling
 super.init(price: price)
 }
 override func taste() -> String {
 return ("This Cake has the best \(filling) filling.")
 }
}

We created the first taste method in the Dessert class, and overrode it in both IceCream and Cake. Let’s create a for loop to show this.

Swift
for desert in desserts {
 print(desert.taste())
}

Notice how the desserts of different child classes have different taste() statements because we overrode the taste method in the child classes.

That's it!

So that’s polymorphism. The idea of parent and children classes, which only applies to classes, not structs.