3

I am implementing a protocol and providing some optional methods in swift but then I am implement these optional methods in derived class. When I call a protocol method it is calling extension method not the derived class method.

protocol ProtocolA {
    func method1()
    // Optional
    func method2()
}
extension ProtocolA {
    func method2(){
        // It comes here, instead of class B method2.
        print("In method 2 - Protocol A")
    }
}

class A : ProtocolA {
    func method1() {
        print("In method 1 - class A")
    }
}

class B : A {
    func method2() {
        print("In method 2 - Class B")
    }
}

var a : A = B()
// It should call - In method 2 - Class B but the output is "In method 2 - Protocol A"
a.method2()
sohail.hussain.dyn
  • 1,411
  • 1
  • 16
  • 26

1 Answers1

0

First you should implement the method on Class A for on class B you can override the method for example:

protocol ProtocolA {
    func method1()
    // Optional
    func method2()
}
extension ProtocolA {
    func method2(){
        // It comes here, instead of class B method2.
        print("In method 2 - Protocol A")
    }
}

class A : ProtocolA {
    func method1() {
        print("In method 1 - Class A")
    }

    func method2(){
        // It comes here, instead of class B method2.
        print("In method 2 - Class A")
    }
}

class B : A {
    override func method2() {
        print("In method 2 - Class B")
    }
}

var a : A = B()
a.method2()

or use the class B as a Type directly:

protocol ProtocolA {
    func method1()
    // Optional
    func method2()
}
extension ProtocolA {
    func method2(){
        // It comes here, instead of class B method2.
        print("In method 2 - Protocol A")
    }
}

class A : ProtocolA {
    func method1() {
        print("In method 1 - Class A")
    }

//  func method2(){
//      // It comes here, instead of class B method2.
//      print("In method 2 - Class A")
//  }
}

class B : A {
    func method2() {
        print("In method 2 - Class B")
    }
}

var b : B = B()
b.method2()

The problem is the runtime choose the function that was implemented based on the Type of variable.