Reputation: 726929
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?
Upvotes: 6
Views: 202
Reputation: 3038
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.
Upvotes: 4
Reputation: 729
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.
Upvotes: 4