override a method on a subclass in swift

To override a method on a subclass in Swift, you need to follow these steps:

  1. Declare your subclass and make it inherit from the parent class.

  2. Override the method you want to modify by declaring a new method with the same signature as the parent method. Use the override keyword in front of the method declaration.

  3. Add your modified code inside the method block.

Here's an example of how to override the description method in a Vehicle class to customize the description on a Car subclass:

main.swift
class Vehicle {
    var type: String
    
    init(type: String) {
        self.type = type
    }
    
    func description() -> String {
        return "This is a \(self.type) vehicle."
    }
}

class Car: Vehicle {
    override func description() -> String {
        return "This is a car."
    }
}
301 chars
18 lines

In this example, the Car subclass overrides the description method to return a custom string. When you create a Car object and call the description method on it, it will return "This is a car." instead of the default string from the Vehicle class.

gistlibby LogSnag