I have two options when implementing protocol conformance in Swift, with the same end result:
Here is an example:
public class MyClass : CustomDebugStringConvertible {
... // Something
public var debugDescription : String {
return "MyClass"
}
}
vs.
class MyClass {
... // Something
}
extension MyClass : CustomDebugStringConvertible {
public var debugDescription: String {
return "MyClass"
}
}
Code samples in Swift books tend to concentrate on the first approach; Apple's source code of Swift core reveals that they use only the second approach (see Bool
and Optional
for an example).
Is there a sound way to decide between the two approaches depending on the situation, or is it simply a matter of coding preference?
To create a protocol, use the protocol keyword followed by the name you want and defined by the curly braces. Protocols can be of 2 types: read-only/read-write. Read-only means you can only get the variable, but you cannot set it. Read-write means you can both set and get properties.
As mentioned in Swift's documentation: “You can use protocol extensions to provide a default implementation to any method or computed property requirement of that protocol.” In fact, not only can you provide a default implementation to methods or computed properties defined in the protocol, you can also add new ones.
Protocols are used to define a “blueprint of methods, properties, and other requirements that suit a particular task or piece of functionality.” Swift checks for protocol conformity issues at compile-time, allowing developers to discover some fatal bugs in the code even before running the program.
In Swift, a protocol defines a blueprint of methods or properties that can then be adopted by classes (or any other types). We use the protocol keyword to define a protocol. For example, protocol Greet { // blueprint of a property var name: String { get } // blueprint of a method func message() }
It's more a matter of coding preference and readability. If you think your class is going to be giant, it might make more sense to implement it in an extension so that it's methods do not add clutter to your class. If it is a short class, I would say all in one, because readability is less affected.
I see it mostly as coding preference. In my team here we have started to adopt the second approach. At first I thought it was an odd use of extension but I have come to like it. It keeps the implemented methods of a protocol nicely together and gives the impression that the class itself is smaller (just optics really). I could see some complications or opportunities for confusion if, say, the class has a tableview and you use extensions to implement the datasource and delegate. If someone then subclasses that class, they might not be aware of the extension and see unexpected behavior.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With