Swift 中的 "marker protocol" 是什么?

What is a "marker protocol" in Swift?

我正在搜索一些 Swift 开放源代码,现在看到术语 "marker protocol" 弹出了两次。从上下文来看,我将其推断为出于代码可读性原因而存在的协议,而不是实际执行规则。谁能准确解释 "marker protocol" 是什么以及为什么使用它?

标记协议是从其他 object-oriented 允许协议或接口的编程语言借用的设计模式。这个想法是标记一个 class 以特定方式使用,但不需要 class 通过实现特定方法来提供任何功能。例如,Java 使用这种方法来标记 classes serializable.

这是一个例子:

protocol Marker {}

class One : Marker {
    ...
}
class Two { // No marker
    ...
}
...
if (myObj is Marker) {
    ... // Objects of class One will pass
    ... // Objects of class Two will not pass
}

当标记 classes 的需要通过语言明确解决时,此技术变得不那么重要了。例如,Java 可以使用 annotations 来处理可序列化,就像 C# 使用 attributes 那样,但是该功能当时不可用。

Swift是一种不断进化的语言,有属性,但都是pre-defined。 user-defined 属性的添加将消除对标记协议的需要。