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?