Override object method using Swift protocols and extensions

54 views Asked by At

I would like to override a method that is declared in a framework and implemented in an extension.

Here's what I've tried :

import UIKit

// Code from a dependency

class Object { // UIViewController
    func printSomething() {
        print("something")
    }
}

// My code

protocol SayHelloProtocol {
    func hello()
    func name() -> String
}

extension SayHelloProtocol {
    func hello() {
        print("Hello " + name())
    }

    func name() -> String {
        "someone"
    }
}

class MyHelloObject: Object, SayHelloProtocol {
    override func printSomething() {
        hello()
    }
}

class MyHelloChildObject: MyHelloObject {
    func name() -> String {
        "You"
    }
}

MyHelloObject().printSomething()
MyHelloChildObject().printSomething()

This will print :

Hello someone
Hello someone

But I would like to override the method so it prints :

Hello someone
Hello You

Is it possible to override a method implemented in an extension ?

1

There are 1 answers

2
koen On BEST ANSWER

It works if you add the name() function also to MyHelloObject:

class MyHelloObject: Object, SayHelloProtocol {
    override func printSomething() {
        hello()
    }

    func name() -> String {
        "Someone"
    }
}

class MyHelloChildObject: MyHelloObject {
    override func name() -> String {
        "You"
    }
}