4

I like how Swift lets you define a method in a protocol, then via an extension of that protocol, implement that method. However, specifically for cases where you're defining the protocol and the extension in the same scope and with the same access levels, do you need to define the method in the protocol in the first place?

Consider this code:

public protocol MyProtocol {
    func addThese(a:Int, b:Int) -> Int
}

public extension MyProtocol {
    func addThese(a:Int, b:Int) -> Int{
        return a + b
    }
}

How is that different than this?

public protocol MyProtocol {
}

public extension MyProtocol {
    func addThese(a:Int, b:Int) -> Int{
        return a + b
    }
}

Note: I'm specifically asking about the protocol and extension being defined together in the same scope with the same access levels.

If that wasn't the case--i.e. the extension is in a different scope than the protocol--then obviously only items in the same scope as the extension would get the automatic implementation. That makes sense.

i.e. In Module A:

public protocol MyProtocol {
    func addThese(a:Int, b:Int) -> Int
}

In Module B

internal extension MyProtocol {
    func addThese(a:Int, b:Int) -> Int{
        return a + b
    }
}

All items in Module B that implement MyProtocol would automatically get the implementation for addThese whereas items that implement MyProtocol in a different scope would still have to explicitly satisfy the protocol.

Again, this is specifically around defining a protocol and extension together. Is there a need to define the function in the protocol itself, or is it just considered good practice?

Mark A. Donohoe
  • 28,442
  • 25
  • 137
  • 286
  • Darn, that deleted Martin's comment :/ Here's the blog post he linked to: https://oleb.net/blog/2016/06/kevin-ballard-swift-dispatch/ – Hamish Jan 10 '18 at 19:09

1 Answers1

1

You don't need to define the method in the protocol, you can add methods to protocols using extensions just as you said, I've done it many times. I see it as a convenient way of giving a bit of inheritance to classes that were already conforming to the protocol.

In fact, you can even extend native protocols, such as UITableViewDataSource or UITableViewDelegate. For example, you might want all of your view controllers that handle a table view to have access to one convenient method.

However, for your own protocols, I do recommend keeping these extensions in the same file as the protocol declaration, to better keep track of everything related to the protocol.

If still in doubt you can read the documentation: https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/Extensions.html

Extensions add new functionality to an existing class, structure, enumeration, or protocol type

So I don't believe it's bad practice, you are simply adding new functionality.