Hey!
To start with, I'd like to mention that I'm relatively new to Swift. Saying that, I have about a decade of experience as a developer, where I've used various languages and frameworks and overall I'm pretty familiar with software engineering principles, best practices and design patterns.
In Swift, I've seen a lot of code and examples where protocol conformance is done using extensions. Now, I do understand (and also the docs are very clear on this one) that it can be very useful when working with objects we do not own - such as 3rd part libraries, etc. What I'm struggling to understand is what are the benefits of doing so for objects I do own.
To clarify further, here's a simple example:
Usually when I'm writing a class, and I want it to conform to a protocol (or implement an interface) I'd write something like this:
protocol MyProtocol {
func foo() -> Int
}
class MyClass : MyProtocol {
func foo() -> Int {
return 10
}
}
I think it is very clear to someone who opens the file and reads the code, that the class conforms to MyProtocol protocol.
On the other hand, in many cases I see this:
protocol MyProtocol {
func foo() -> Int
}
class MyClass {
}
extension MyClass: MyProtocol {
func foo() -> Int {
return 10
}
}
At times, the extension isn't even declared at the same file the object is declared at.
I do not see the benefits of doing so, on the contrary, I feel it makes the code harder to understand and perhaps, in some way, violating the Open-Closed principle from SOLID (
software entities (classes, modules, functions, etc.) should be open for extension, but closed for modification
)
Here's an example of the issue:
protocol MyProtocol {
func foo() -> Int
}
class MyClass {
}
extension MyClass: MyProtocol {
func foo() -> Int {
return 10
}
}
class MyOtherClass: MyClass {
// foo here cannot be changed or overridden
func foo() -> Int {
return 5
}
}
It is not possible to override foo inside MyOtherClass, which is expected to be possible.
To summarize, I'd love to hear what the benefits of using extensions for protocol conformance in owned objects is. To me it has a bit of a code smell at this point. Would love to learn otherwise
Thank you for your time and input.