[swift-evolution] [Proposal] Explicit Synthetic Behaviour

Haravikk swift-evolution at haravikk.me
Fri Sep 8 02:46:45 CDT 2017


> On 7 Sep 2017, at 22:02, Itai Ferber <iferber at apple.com> wrote:
> 
> protocol Fooable : Equatable { // Equatable is just a simple example
>     var myFoo: Int { get }
> }
> 
> extension Fooable {
>     static func ==(_ lhs: Self, _ rhs: Self) -> Bool {
>         return lhs.myFoo == rhs.myFoo
>     }
> }
> 
> struct X : Fooable {
>     let myFoo: Int
>     let myName: String
>     // Whoops, forgot to give an implementation of ==
> }
> 
> print(X(myFoo: 42, myName: "Alice") == X(myFoo: 42, myName: "Bob")) // true
> This property is necessary, but not sufficient to provide a correct implementation. A default implementation might be able to assume something about the types that it defines, but it does not necessarily know enough.

Sorry but that's a bit of a contrived example; in this case the protocol should not implement the equality operator if more information may be required to define equality. It should only be implemented if the protocol is absolutely clear that .myFoo is the only part of a Fooable that can or should be compared as equatable, e.g- if a Fooable is a database record and .myFoo is a primary key, the data could differ but it would still be a reference to the same record.

To be clear, I'm not arguing that someone can't create a regular default implementation that also makes flawed assumptions, but that synthesised/reflective implementations by their very nature have to, as they cannot under every circumstance guarantee correctness when using parts of a concrete type that they know nothing about.

>> Reflective/synthesised default implementations must by their very nature make assumptions about a concrete type that are not cannot be guaranteed to be correct. The properties and methods they may end up interacting withmay have nothing at all to do with the protocol. Equatable remains by far the simplest example; just because a developer has used equatable properties does not guarantee that all of them should be compared during a check for equality.
> In the same way that you might consider synthesized conformances to overreach into a type and touch things which are not related to a protocol, default implementations can be considered underreach in that they don’t know anything about properties which are necessary for providing a correct implementation.

If more information is necessary to provide a correct implementation, then a default implementation shouldn't be provided. This is what unimplemented properties and methods are for; either getting the developer to provide the missing information, or getting them to implement the correct behaviour.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20170908/256115a3/attachment-0001.html>


More information about the swift-evolution mailing list