0

How to resolve in swift (2.0) that case: we have two protocols:

protocol SuperDelegate{
     func handleSuccess(rsp: BaseRsp)
}

protocol ChildOfSuperDelegate: SuperDelegate {
    func handleSuccess(rsp: ChildOfBaseRsp)
}

and some place in code where we want do:

class A{
    var delegate:SuperDelegate?

    func foo(){
        delegate?.handleSuccess(childOfBaseRspObj)
    }
}

class Xyz:ChildOfSuperDelegate{
     func handleSuccess(rsp: ChildOfBaseRsp){
        print("Great!")
     } 
}

but compiler not founding inheritence in protocols (handleSuccess have function with base and child parameters) there are compile error:

Type 'Xyz' does not conform to protocol 'SuperDelegate'

. How to resolve them? What is the best way to only implements ChildOfSuperDelegate methods but class "A" use SuperDelegate variable.

Meybe I must use generic types to have somethink like inheritance in protocols.

luky0007
  • 79
  • 1
  • 7
  • The parameter type is different between the protocols parameters – Luca D'Alberti Feb 06 '17 at 11:47
  • Well your `delegate` says that it has a method `handleSuccess` which takes a `BaseRsp`, but `Xyz` says that it can *only* take a `ChildOfBaseRsp`. There's no way this can work safely. `Xyz` simply doesn't satisfy the requirement of `func handleSuccess(rsp: BaseRsp)`. – Hamish Feb 06 '17 at 11:47
  • I know. But how to resolve them, I must have superDelegate, and somethink like inheritance in protocols, Is generic Types a good idea? – luky0007 Feb 06 '17 at 11:52
  • make the type same. – Rocky Balboa Feb 06 '17 at 11:52
  • I doubt whether you use a good approach. I think it's better to use protocols extensions in such cases, to avoid inheritance and get "abstract class" like behavior. It's mentioned here: http://stackoverflow.com/questions/24110396/abstract-classes-in-swift-language – marcinax Feb 06 '17 at 15:00

1 Answers1

0

Here your protocol ChildOfSuperDelegate is inherited from SuperDelegate and though it is a protocol it doesn't implement its methods. But when you inherit from ChildOfSuperDelegate you have to implement method of SuperDelegate as well ChildOfSuperDelegate.

So do like this:

class Xyz:ChildOfSuperDelegate{
  func handleSuccess(rsp: BaseRsp) {
    //do stuff 
  }

func handleSuccess(rsp: ChildOfBaseRsp){
     print("Great!")
  }
}
Rocky Balboa
  • 784
  • 10
  • 25
  • **I know that. It's not I looking for**. I want to call protocol function with poliformism, f.ex: `delegate.handleSuccess(rspChildOfBaseRspObj) or delegate.handleSuccess(anotherChild)` but my delegate is object implements SuperDelegate (only). So question is why protocols not have polimorphic metods and what is walkarounds – luky0007 Feb 08 '17 at 15:30