Uploaded image for project: 'Swift'
  1. Swift
  2. SR-11385

Automated conformance can be hijacked by extension protocol conformances that import matching members

    XMLWordPrintable

    Details

      Description

      Let the standard library protocols with automatic conformance (SLPwAC) be defined as those matching protocols from the Standard Library (that's Equatable, Hashable, Encodable, and Decodable as of this writing)

      For the SLPwAC, said automation is implicit. You just have to declare the conformance and not bother adding any corresponding members. But if a different protocol has a members defined in an extension that match the signature of members from the SLPwAC, then automatically-defined implicit member definitions are cancelled and the extension's code is used, even if it customizes the member in a way the user doesn't want.

      protocol Sucker {}
      
      #if false
      extension Sucker {
          static func == (lhs: Self, rhs: Self) -> Bool {
              print("Sucker")
              return true
          }
      }
      #endif
      
      struct MyType: Equatable {}
      extension MyType: Sucker {}
      
      MyType() == MyType()
      

      (It doesn't matter if MyType adds its Equatable conformance in the primary definition or in an extension block.  It doesn't matter if Sucker refines Equatable or not.)

      If you change the compilation test to true, then "Sucker" will be printed.

      I suggest that we add an explicit declaration in nominal types that posts the desire to use the compiler-generated versions of SLPwAC members, with the same precedence as an explicitly written member in the target type (which out-prioritizes any imported definitions from protocols).

      // Example:
      struct MyType: Equatable {
          //...
          publish default Equatable
      }
      

      We could depreciate the current implicit behavior and maybe end it later.

        Attachments

          Issue Links

            Activity

              People

              • Assignee:
                Unassigned
                Reporter:
                CTMacUser Daryle Walker
              • Votes:
                0 Vote for this issue
                Watchers:
                2 Start watching this issue

                Dates

                • Created:
                  Updated: