在哪里实现 Swift 协议? [英] Where to implement Swift protocols?

查看:74
本文介绍了在哪里实现 Swift 协议?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Swift 中实现协议一致性时,我有两个选择,最终结果相同:

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.

这是一个例子:

public class MyClass : CustomDebugStringConvertible {
    ... // Something
    public var debugDescription : String {
        return "MyClass"
    }
}

对比

class MyClass {
    ... // Something
}
extension MyClass : CustomDebugStringConvertible {
    public var debugDescription: String {
        return "MyClass"
    }
}

Swift 书籍中的代码示例倾向于关注第一种方法;Apple 的 Swift 核心源代码表明他们只使用第二种方法(请参阅 BoolOptional 为例).

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?

推荐答案

我主要将其视为编码偏好.在我的团队中,我们已经开始采用第二种方法.起初我认为这是扩展的奇怪用法,但我开始喜欢它.它将协议的实现方法很好地结合在一起,并给人的印象是类本身更小(实际上只是光学).如果类有一个 tableview 并且您使用扩展来实现数据源和委托,我会看到一些复杂情况或混淆的机会.如果有人随后对该类进行子类化,他们可能不知道该扩展并会看到意外行为.

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.

这篇关于在哪里实现 Swift 协议?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆