With protocols, one class/struct can be used as different things. For example, the String
struct conforms to soooo many protocols!
Comparable
CustomDebugStringConvertible
Equatable
ExtendedGraphemeClusterLiteralConvertible
Hashable
MirrorPathType
OutputStreamType
Streamable
StringInterpolationConvertible
StringLiteralConvertible
UnicodeScalarLiteralConvertible
This means that String
can be used as 11 different things! When a method needs any one of the above protocols as a parameter, you can pass in a string.
"But I can just create a god class that has all of the methods that the protocols have!" you argued. Remember, you can only inherit from only one class in Swift, and multiple inheritance is just so dangerous to use that it can make your code super complex.
Also, with protocols, you can define your custom behaviour of the class. String
's hashcode
method is not the same as that of Int
. But they are both compatible with this function:
func doStuff(x: Hashable) {
}
That is the true wonder of protocols.
Last but not least, protocols make sense. Protocols represent an "is a kind of" or "can be used as" relationship. When X can be used as Y, it makes sense that X conforms to protocol Y, right?