Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is a "marker protocol" in Swift?

I was searching through some Swift open source code and have now seen the term "marker protocol" pop up twice. From context I'm inferring it as a protocol that exists for code readability reasons, not actually to enforce rules. Can anyone explain exactly what a "marker protocol" is AND why it is used?

like image 455
tnev Avatar asked Mar 13 '23 12:03

tnev


1 Answers

Marker protocol is a design pattern borrowed from other object-oriented programming languages that allow protocols or interfaces. The idea is to mark a class for use in a specific way, but without requiring the class to provide any functionality by implementing specific methods. For example, Java used this approach to mark classes serializable.

Here is an example:

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
}

This technique is becoming less relevant when the need to mark classes is addressed explicitly by language. For example, Java could have used annotations for dealing with serializability, in the same way that C# did it using attributes, but the feature had not been available at the time.

Swift is an evolving language that has attributes, but all of them are pre-defined. An addition of user-defined attributes will eliminate the need for marker protocols.

like image 125
Sergey Kalinichenko Avatar answered Mar 29 '23 14:03

Sergey Kalinichenko