[swift-evolution] [Proposal] Explicit Non-Default-Implemented Protocol Requirements

Gor Gyolchanyan gor.f.gyolchanyan at icloud.com
Wed Aug 2 03:53:57 CDT 2017


Good day, swift community!
This time, I'd like to bring your attention to an everyday problem which, I'm sure, you've all dealt with at some point.

Motivation

Many protocols have a lot of default-implemented requirements so that they can be customized, which would otherwise be impossible to do.
For example, the Comparable protocol, which (considering its inheritance of Equatable) states a requirement of ==, !=, <, <=, >, and >=, only requires implementation of == and <, because all others have default implementations in terms of these two. This forces the user to either memorize the exact set of mandatory requirements or, in case of more complicated protocols like Collection, constantly look up the documentation and hope that it has a section outlining how to conform to it.
Conversely, the author of the protocol needs to manually keep track of the requirements and their default implementations to ensure that the ones that have to be mandatory stay mandatory and the rest of the requirements stay default-implemented, which is also a tedious and error-prone work.

Proposed Solution

I'd like to propose the ability to mark select protocol requirements as default, which would cause the following effects:
The compiler will emit a compile-time error if a default implementation is not available in a non-constrained protocol extension in the same file and provide a fix-it for inserting a template.
If a conforming type does not implement all requirements of the protocol, the compiler will not produce fix-its for inserting a template for any default requirements.

Example

// Equatable.swift

protocol Equatable {

	static func == (_ some: Self, _ other: Self) -> Bool

	default static func != (_ some: Self, _ other: Self) -> Bool
	^ error: missing implementation of a default requirement `!=`; fix-it: insert a default implementation

}

extension Equatable {

	static func != (_ some: Self, _ other: Self) -> Bool {
		[Your Code Here]
	}

}

// Something.swift

struct Something: Equatable {
^ error: missing implementation of a non-default requirement `==`; fix-it: insert an implementation

}

extension Something {

	static func == (_ some: Something, _ other: Something) -> Bool {
		[Your Code Here]
	}

}

Cheers,
Gor Gyolchanyan.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20170802/d0192443/attachment.html>


More information about the swift-evolution mailing list