The pitch introduces the conformance
keyword as a short-hand for a programmer intent. Quoting the pitch:
The conformance
keyword means: "this declaration is intended by the programmer to fulfill a protocol requirement".
I have started to wonder if the intent was well-defined, and the keyword well-chosen, after @pyrtsa has reminded us that many users struggle with the subtle distinction between protocol requirements and protocol extensions.
Most readers of the forum are now very familiar with Swift protocols, and know how and when to expect static or dynamic dispatch. But we also know that this is a difficult step on the way to Swift proficiency.
I can imagine a Swift course about static vs. dynamic dispatch that goes this way:
[TEACHER] When you want to make sure that your method is dynamically dispatched, do insert the xxxx
keyword in front of your declaration, like this:
extension Rectangle: Shape {
// Dynamic dispatch for the draw() method
xxxx func draw() { ... }
}
If the compiler does not produce any error, you're good to go. If the compiler produces an error, then you probably missed the condition for dynamic dispatch: the dynamic method must be declared inside the protocol definition, not in an extension.
If I sum up:
// Enable dynamic dispatch by defining the method inside the protocol definition
protocol Shape {
func draw()
}
// Grant your conforming types with dynamic dispatch with the xxxx keyword:
extension Rectangle: Shape {
xxxx func draw() { ... }
}
Please forgive this foray into the realm of the imaginary.
Yet, I think that the correct wording for the conformance intent should be "this declaration is intended by the programmer to be dynamically dispatched".
Dynamic dispatch is the intent. The conformance is a mean that achieves this intent.
Dynamic dispatch is also a frequent cause of struggle for Swift newcomers. By making the intent of dynamic dispatch explicit with a keyword that looks like it does, we'd greatly help those newcomers.
By this line of reasoning, a better keyword than conformance
would just be... dynamic
. But Swift already uses dynamic
for ObjC runtime.
So why not just... dyn
:
protocol Program {
func run()
}
struct HelloWorld: Program {
// OK
dyn func run() { ... }
// error: function crash() does not fulfill any requirement of the protocol 'Program'.
dyn func crash() { ... }
}
dyn
is less a mouthful than conformance
. It is just as abbreviated as func
and var
. It has the potential for avoiding hours of misunderstanding in many young Swifters.