O'Reilly logo

Mastering Swift 4 - Fourth Edition by Jon Hoffman

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Overriding methods

Let's look at how we can override a method. We will start by adding a getDetails() method to the Plant class that we will then override in the child classes. The following code shows the code for the new Plant class:

class Plant { 
  var height = 0.0  
  var age = 0 
  func growHeight(inches: Double) {  
    self.height += inches; 
  } 
  func getDetails() -> String {  
    return "Plant Details" 
  } 
} 

Now, let's see how we can override the getDetails() method in the Tree class:

class Tree: Plant {  
  private var limbs = 0 
  func limbGrow() { 
    self.limbs += 1 
  } 
  func limbFall() {  
    self.limbs -= 1 
  } 
  override func getDetails() -> String { 
    return "Tree Details" 
  } 
} 

The thing to note here is that we do not use the override keyword in the Plant class because it ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required