Where to implement Swift protocols?

落花浮王杯 提交于 2019-12-10 13:27:15

问题


I have two options when implementing protocol conformance in Swift, with the same end result:

  • Implement the protocol within the class - that is, state the conformance at the top of class definition, and put implementation inside the class body, or
  • Implement the protocol in an extension - that is, code up protocol conformance entirely outside the class.

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?


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/37281671/where-to-implement-swift-protocols

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!