Default implementations in protocol declarations

Brief summary: Make the following valid Swift (the meaning should be obvious):

protocol Person {
   var firstName: String { get }
   var lastName: String { get }
   func printFullName() {
       print(firstName + " " + lastName)
   }
}

Imho there's a broad consensus that this would be desirable (although I'm sure some people will argue against such a change), and it would solve parts of an issue that got revived some time ago (Introducing role keywords to reduce hard-to-find bugs - depending on how depressing this thread turns out to be, I might start another one for the second part ;-)

Two years ago, there already was a vague hope to get this "feature" for Swift 3 (Default implementation for protocols), so I guess that is enough time to check how the perspective is now.

1 Like

I'm so for the default role keyword and nesting protocols in other types and vice versa. If we get the role keyword then default implementation in protocol declaration becomes pure sugar change to the language. ;)

3 Likes

Self-fullfilling prophecy: Why do server side projects seem to reinvent everything? - #8 by Tino

;-)

My perspective is that role keywords are quite a big change which pushes Swift into the direction of "public final static void main", whereas the alternatives are not only more powerful, but also simpler ¯\(ツ)

We're not going to remove default implementations in extensions and I think the default role keyword is something that helps everyone to verify that the default implementation was accepted by the compiler and you have not done any mistakes. Default implementation in the protocol declarations is just the same as you'd have an extension for a protocol with default members.

It just happens to be much less code and repetition... with implementation inside the protocol, that class of errors just can't happen, without adding new concepts to the language.
Imho Swift shouldn't reach for new keywords whenever a tiny inconvenience is discovered, but rather increase internal consistency.

I would prefer the function body inside the protocol rather than default keyword in an extension.

3 Likes