David Silva
David Silva

Reputation: 2017

Overriding the method - unexpected behaviour

I have code like this:

class A {
    func method() { print("method from A") }
}

class B: A {
    override func method() { print("method from B") }
}

class C: A {
    override func method() { print("method from C") }
}


func run (_ obj: A) {
    doIt(obj)
}

func doIt(_ obj: A) {
    print("specific logic when object of A class")
    obj.method()
}

func doIt(_ obj: B) {
    print("specific logic when object of B class")
    obj.method()
}

func doIt(_ obj: C) {
    print("specific logic when object of C class")
    obj.method()
}


let obj = C()
run(obj)

I am getting output:

specific logic when object of A class method from C

but i would expect:

specific logic when object of C class method from C

How should I change the code to get this behavior?

Upvotes: 0

Views: 75

Answers (2)

TNguyen
TNguyen

Reputation: 1051

Although polymorphism is the best approach, here is another way you can do it

class A {
    func method() { print("method from A") }
}

class B: A {
    override func method() { print("method from B") }
}

class C: A {
    override func method() { print("method from C") }
}


func run<T: A>(_ obj: T) {
    doIt(obj)
}

func doIt<T: A>(_ obj: T) {
    print("specific logic when object of \(T.self) class")
    obj.method()
}

let obj = C()
run(obj)

Upvotes: 1

matt
matt

Reputation: 535306

The problem is merely that you have made doIt three loose functions. Instead, make it three methods of the three classes:

class A {
    func method() { print("method from A") }
    func doIt() {
        print("specific logic when object of A class")
        self.method()
    }
}

class B: A {
    override func method() { print("method from B") }
    override func doIt() {
        print("specific logic when object of B class")
        self.method()
    }
}

class C: A {
    override func method() { print("method from C") }
    override func doIt() {
        print("specific logic when object of C class")
        self.method()
    }
}


func run (_ obj: A) {
    obj.doIt()
}

Now polymorphism does the work for you.

Upvotes: 2

Related Questions