0

I have the following code:

protocol MyProtocol {
    // Are the following 2 declarations necessary?
    var myProperty: Int { get }
    func myFunc()
}

extension MyProtocol {
    var myProperty: Int {
        return 1
    }
    func myFunc() {
        print("hello")
    }
}

Since I am providing default implementations in the extension, I can access either the property or the function from a conforming class even when they're not declared in the protocol body. Is it necessary therefore to declare the stored property and function in the body of the protocol? Any case where not declaring them will pose an issue? Thanks for the pointers.

yohannes
  • 1,022
  • 11
  • 13
  • Also related: https://stackoverflow.com/questions/34847318/swift-protocol-extension-method-dispatch-with-superclass-and-subclass, https://oleb.net/blog/2016/06/kevin-ballard-swift-dispatch/ – Martin R Jul 18 '17 at 07:14
  • @MartinR I read both docs but it doesn't answer the concern I have, at least to my understanding. So, in the case I outlined above, is it necessary or not to declare the variable or the function if they're defined in the extension as default implementations. – yohannes Jul 21 '17 at 08:17
  • Are MyProtocol and FirebaseDatabaseStorageProtocol meant to be the same in your question? – Martin R Jul 21 '17 at 08:29
  • @MartinR Yes (I just edited the extension name. They're supposed to be the same name) – yohannes Jul 24 '17 at 09:55
  • 1
    I think it is clearly explained in the Q&A that I chose as duplicate: You don't *have* to define the properties in the protocol (as requirements), but the behaviour is different if you do it or not (dynamic vs static dispatch). – Martin R Jul 24 '17 at 09:58

0 Answers0