Pre-Pitch: Explicit protocol fulfilment with the 'conformance' keyword

In both of these cases, the desired near-miss diagnostics already trigger when the protocol conformance is declared in its own extension (or, should—I haven’t tested the exact example, and if they don’t we should file a bug to improve the existing diagnostics).

In my view, these near-miss diagnostics are one of the really nice benefits of implementing conformances in dedicated extensions. One way of looking at it is that Swift already implements the feature you’re pitching, except that it’s spelled by nesting the member inside an extension instead of prefixing with a keyword such as conformance.

There is one key shortcoming and one key advantage of the current design as compared to your pitch that I can think of:

The shortcoming is that stored properties cannot be declared as protocol-conforming implementations in an extension; this is a limitation that I and many others have long wished to be lifted for several other reasons (my very niche own pet reason is that it will allow anything expressible as fileprivate to be spelled without using that access level). I hope and expect that same-file extensions will be able to declare stored properties before long and would want that to come to the language regardless of what other near-miss features are added.

The advantage is that extension allows the user to declare not just that a member conforms a requirement of some protocol, but rather which protocol (or, even, protocols). This is, as you note, a shortcoming of your pitched design which has already been solved by the existing design.

(Another advantage, which I don’t think needs to be dwelled on except parenthetically, is that the existing design doesn’t require any additional keyword or other syntax—it’s simply making what users already do work better by producing helpful diagnostics when user intention is recognized.)


Maybe this is tangential, but it seems a little weird to me that extension A: SomeProtocol { ··· } does two things that are actually more or less orthogonal: adding an extension, and adding a protocol conformance, which may or may not be satisfied by things in that particular extension.

Right now you can do silly stuff like this:

struct Thing { ··· }

extension Thing: ProtocolA {
  // things that satisfy ProtocolB

extension Thing: ProtocolB {
  // things that satisfy ProtocolA

...which I think can conceivably happen to code that grows over time and gets reorganized without enough attention to detail.

It makes me wonder if there would be value in being able to say "all members needed to satisfy protocol X are exclusively in this extension (and maybe also in the main declaration)". (I'm not suggesting all extensions should be like this; frequently it's useful to declare conformance using elements that a type already has)


Perhaps permit the declaration name to be qualified with the protocol type?:

protocol P {
    func foo()

struct S: P {
    func { }

Aside from error messages, the protocol name could also support refactoring, completions, and navigation.

This doesn't help when the same declaration complies with multiple protocols, but perhaps that's an anti-pattern.


+1 for the pitch. As a bike shed name also consider "conforming":

conforming func foo() {...}

I wonder how we handle this situation with override and could we do the same with conformance?


I don't think you can have this problem. While you don't know which class or classes in the chain have a function with the same signature, you do know the one being overridden is the nearest ancestor which has such a function, of which there can only be one.

Thanks @xwu. The pitch does not rely on any code structure, such as fulfillments grouped in dedicated extensions, for several reasons:

Indeed it is not always possible to declare a fulfillment in an extension. A stored property that fulfills a protocol requirement, for example, can not be declared in an extension. But even if this would becomes possible eventually, I wouldn't rely on extensions anyway.

First, even if extension grouping could help with near-misses (it does not), it would not help with the second described problem, due to protocol evolution. I'm talking about functions that becomes useless because one requirement of a protocol has been deleted, and functions that need to update their signature. Should we start to require that extension T: P { ... } can only contain P fulfillments? Even people who group protocol conformances into a dedicated extension happen to declare more related methods inside it - and I'm not sure this would be considered "bad style".

Next, the pitch does not favor one particular programming style. Grouping fulfillments in extensions is frequent, in some social groups, but not universal:

  • Some code crunching tools (I think of jazzy) don't always produce good results when conformances are declared in an extension. I've seen myself declaring all conformances upfront, at the location of the type declaration, and provide fulfillments elsewhere. It's not a personal preference, it's a pragmatic decision based on my constraints at the moment I was writing this code:

    struct T: P { ... }
    // "Detached" P conformance
    extension T { ... }
  • The language does not mandate any programming style. The language comes first, style comes second, and can vary. Grouping fulfillments in an extension is not required by the language. I do not know of another language feature that requires a particular style to be enabled.

  • Not all users have the same skills, or time, to polish their code. Requiring a particular style (grouping fulfillments in an extension) for enabling language features could be seen as elitist, or ableist, or pedantic for no good reason.

  • If the compiler would help solving the problems described in the pitch by emitting warnings or errors, based on extension grouping, then a simple move of code (copy and paste) would create or resolve this diagnostic. I'm afraid this would bring more confusion than good: how can the same identical function be correct here, and incorrect there? Make you your mind, compiler!


Thank you @wes1. Yes, a similar idea is explored in the future directions of the pitch:

struct S: P {
    conformance(P) func foo() { }

Your idea is good, but I still prefer conformance:

  • With conformance, you do not have to always repeat the protocol name. This could be tedious if you have to write a dozen such methods, in order to fulfill the requirement of a protocol with a very long name.
  • With conformance, we can suggest in the future directions a path to a public version of @_implements(ProtocolName, Requirement). Your proposed syntax can not be extended in the same way.

English is not my mother tongue, and I always read override as a name when in front of func or var (you never know what the brain of a stranger will do!). Hence conformance.

If native speakers see override as a verb, then conform would be better. If an adjective, conforming will certainly do. I'll let the English-native crowd choose, here :-)


+1 for the pitch

As a future direction, maybe we can satisfy protocol requirements by annotating dynamicMemberLookup subscripts with the conformance keyword.

protocol Requirement {
    var someProperty: Double { get }
    func someMethod(argument: Int) -> Bool

class Implementation: Requirement {
    conformance subscript(dynamicMember dynamicMember: String) -> Any { /* return something accordingly */ }
    conformance subscript(dynamicMember dynamicMember: String) -> Callable { Callable() }

class Callable {
    func dynamicallyCall(withKeywordArguments args: KeyValuePairs<String, Any>) -> Any { /* return something accordingly */ }


Pitch was edited with a new "The conformance keyword could be made able to "auto-fix" some near misses" paragraph in the future directions.

Maybe the pitch would be better if I made explicit an underlying idea regarding documentation.

The conformance keyword is pitched as optional. One does not have to use it. One has benefits using it, because it reveals some present or future mismatches between the programmer intent, and what the compiler sees. By "present mismatch", I mean typos and near-misses. By "future mismatch", I mean code that must change because a dependency has changed the definition of a protocol.

It is a tool that I initially intended for three groups of people:

  1. Programmers who are aware of the benefits of the keyword, for their own code base.
  2. Documentation writers, who would start recommending the use of the conformance keyword in the documentation of some protocols, when relevant.
  3. Clueless documentation readers, who use the conformance keyword because that's what the sample code says in the documentation. And that's as good for them as it is good for the programmers who are aware of what they are doing.

The benefits of conformance for the first group have been explained above.

The benefits of conformance for the documentation writers is two-fold:

  1. Some documentation can be simplified. The example below comes from GRDB (original), and was considered necessary due to the high risk of miss due to type-inference:

    Note: make sure the databaseSelection property is explicitly declared as [any SQLSelectable]. If it is not, the Swift compiler may silently miss the protocol requirement, resulting in sticky SELECT * requests.

    This paragraph aims at avoiding this kind of bug:

    struct Player: TableRecord {
        // MISS: '[Column]' is not '[any SQLSelectable]'
        static let databaseSelection = [Column("id"), Column("name")]

    The conformance keyword would enter the sample code provided in the documentation. When the reader follows the advice, it is for their own benefit.

  2. Migration guides can be simplified. Again, consider this GRDB example (original):

    It is no longer possible to override persistence methods such as insert or update. Customizing the persistence methods is now possible with callbacks such as willSave, willInsert, or didDelete [...].

    [When upgrading] you have to remove the methods below from your own code base: [followed by a list of now-retired customization points].

    Of course the GRDB author is sorry to introduce breaking changes. That's why there is a migration guide. This guide would have been much easier to write if users could have used conformance before. The compiler would have shown the obsolete requirements without any ambiguity, guiding the user in the upgrade. Without it, an exhaustive list of functions that need to be updated is difficult to build (even if one groups conformances in dedicated extensions).

1 Like

What about this reunion of our ideas:

The initial pitch was: the conformance keyword looks for statically-known protocol requirements at the location it is used (and errors out if the declaration has no match).

When used inside an extension that declares a protocol conformance, we could have the conformance keyword perform requirement lookup in those protocols only.

To illustrate, consider the following program. It compiles without error with the pitch as written. But it would not with the suggested amendment:

protocol Foo { func foo() }
protocol Bar { func bar() }

struct S { }

extension S: Bar { }
extension S: Foo {
    conformance func foo() { }
    // Initial pitch: no error
    // Amended pitch: function bar() does not fulfill any 'Foo' requirement.
    conformance func bar() { }

I'm still not 100% convinced, because I do not like the idea that moving a declaration can make it valid or invalid. Yet this change would help solving some ambiguities that are discussed in the "Known Limits" paragraph of the pitch. The balance is difficult.

Following the same idea, we could have:

extension Foo where Self: Bar {
    // Conformance lookup performed in Foo and Bar only
    conformance func bar() { ... }

extension Foo {
    // Conformance lookup performed in Foo and Bar only
    conformance func bar() where Self: Bar { ... }

This amendment, if implemented later, would be a breaking change (since some code would stop compiling). This means it must come with the initial proposal, or not at all (making the implementation more difficult). I humbly let the community decide if it's worth it.


Can conformance be added in protocol extensions for default implementations? Also, I think it’d be nice if we could have conformance extensions, which I think would handle the design pattern outlined by @xwu. Overall, this feature has a lot of promise. I’m interested to see if there are benefits to compilation times using this approach. Additionally, adoption is another important question. I think conformance should become the default as it aids readability, diagnosing near misses and potentially the compiler. If we decide that this keyword should be required, then features such as autocomplete and migration strategies should be discussed to facilitate adoption.



conformance extension MyType: SomeProtocol {
  func ...
  var ...

…could be sugar for

extension MyType: SomeProtocol {
  conformance func ...
  conformance var ...

… and that such a "conformance extension" would produce diagnostics if it included (non-private) members that did not conform to the protocol(s) listed?


This looks nice at first sight (maybe as a future direction, since this does not look required for the pitch to provide value).

Yet beware: such a conformance extension would ONLY accept declarations that fulfill requirements. This is the hard version of the "group protocol conformances in extensions" styling, because even related methods would become forbidden in such an extension:

conformance extension SortedArray: Collection {
    var first: ...  // OK
    var last: ...   // OK
    var median: ... // error: property 'median' does not fulfill any protocol requirement. 

To me, this is the exact point were something nice that always help turns into an ill-designed tool that frequently annoys. I let the community consider if they prefer something good or something too perfect.

As you say, @sveinhal, we'd ignore methods that do not match the visibility of the protocol:

conformance extension SortedArray: Collection {
    var first: ...  // OK
    var last: ...   // OK
    private func someHelper() { ... } // OK

This is a great pitch, and given the precedent of override, seems like maybe it was an oversight in the original Swift implementation. I like that it is opt-in for compatibility, but would also like to see a way to opt-in to require this.

I do think we should move directly to including the conforming protocol too, as it solves a lot of remaining problems and can leverage the implementation for @_implements.

Maybe besides the point for the pitch at hand, but for whatever it's worth: I actually prefer this hard line. Allow for private implementation details such as helper functions, but everything that is not part of the implementation, or privately aids the implementation, should be kept outside the extension, imho.


This is true. It would be tricky to distinguish between helper methods and methods that are actually intended to conform to another protocol.

I have had cases where I have two protocols that are very closely related, and I ended up moving methods from one protocol to the other (kinda like table view data source vs delegate - the line can be a bit blurry). With such a change, any protocol-specific extensions are now incorrectly organized, but the compiler doesn't care. So I'm looking for a way to express my intent to the compiler.


I hit this again the other day. We have really strange witness matching that often feels inconsistent.

For example, if you have a protocol requirement which accepts a concrete type, a generic method can witness it:

protocol MyProtocol {
  func doSomething(_: String)

struct MyStruct: MyProtocol {
  // Works, because String conforms to StringProtocol
  func doSomething<S: StringProtocol>(_: S) { fatalError() }

So you might expect, if there is a protocol requirement which returns an existential, that a method which returns a concrete conforming type would also be able to witness it:

protocol MyProtocol {
  func doSomething() -> any StringProtocol

struct MyStruct: MyProtocol {
  // Computer says no.
  func doSomething() -> String { fatalError() }

If the requirement has a default implementation, the type still conforms, but resolves to an unexpected implementation :frowning:

The idea of only warning about these mismatches in extensions does not seem like an adequate solution, to me. Some types are designed to perform one task and be written in a single, compact declaration - so it is unusual that anybody would split the implementation up across extensions, and hence they would not receive any diagnostics. Types declared inside functions don't support extensions at all:

func someFunction() {
  struct MyStruct {}
  extension MyStruct {}
  error: declaration is only valid at file scope

Maybe this is what you are looking for: Pre-Pitch: Explicit protocol fulfilment with the 'conformance' keyword - #14 by gwendal.roue

extension T {
     // Requires any conformance
     conformance func foo() { ... }

extension T: MyProtocol {
     // Requires a MyProtocol conformance
     conformance func foo() { ... }

The pitch has not been amended with this feature yet - I'm still not sure it should belong to the pitch at this point.