- Oct 14, 2013
The Apple documentation states one needs to implement the static function ==(lhs:rhs. I do not understand why the function needed to be static. It aims at comparing instances anyway.
It still puzzles me. Being a static function implies you would code Struct == Struct which totally makes no sense. It is logical nevertheless as a static function is called on the structure itself like Struct.==The short answer is that's what 'protocol Equatable' requires. I believe this has changed from older versions of swift where operators were global functions. Having the func be static reinforces the fact that the comparison operator doesn't modify its parameters (but I'm not really sure that's why it is that way).
The static keyword allows the compiler to use the existing universal lookup for an equatable call from a protocol as if it were any other method or function, satisfying the above issues without adding additional bloat.We initially considered requiring users to declare a global "trampoline" operator for each operator inside their protocols. This operator would be generic and constrained to that protocol type and would use the static types of its actual arguments to dispatch to the correct implementation. However, this is a burden on protocol authors to provide these stub functions that are purely an implementation detail.
Therefore, we can achieve the performance improvements by making that insight part of the semantic model: when we find all operators, we also find the operators in the protocols themselves. The operators in the protocols are naturally generic; e.g., the Arithmetic + effectively has a generic function type like this:
<Self: Arithmetic>(Self, Self) -> Self
Then, we say that we do not consider an operator function if it implements a protocol requirement, because the requirement is a generalization of all of the operator functions that satisfy that requirement. With this rule, we’re effectively getting the same effects as if users had declared trampoline operators, but it's automatic.
This link turned out to be awesome. Thank you.This evolution ticket may give you answers: https://github.com/apple/swift-evol...sals/0091-improving-operators-in-protocols.md