add a method to a subclass in swift

To add a new method to a subclass in Swift, you can simply define the method in the subclass using the override keyword. This tells Swift that you want to override the method that is inherited from the parent class, and replace it with your own implementation.

Here's an example:

main.swift
class ParentClass {
  func someMethod() {
    print("This is a method from the parent class")
  }
}

class ChildClass: ParentClass {
  override func someMethod() {
    super.someMethod() // Call the parent implementation first
    print("This is a method from the child class")
  }
}

let myObj = ChildClass()
myObj.someMethod()
// Output:
// This is a method from the parent class
// This is a method from the child class
423 chars
19 lines

In this example, we have two classes: ParentClass and ChildClass. ChildClass is a subclass of ParentClass. We're adding a new method called someMethod in ChildClass, and using the override keyword to override the implementation from the parent class. In the implementation of our new method, we're calling the implementation from the parent class using super, and then adding some additional functionality.

When we create an object of type ChildClass and call the someMethod method on it, we get both the output from the parent class implementation and the output from our own implementation in the child class.

gistlibby LogSnag