[swift-evolution] Proposal for generic protocols

Joe Groff jgroff at apple.com
Thu Dec 3 16:43:24 CST 2015

> On Dec 3, 2015, at 2:12 PM, Tal Atlas <me at tal.by> wrote:
> With the awesome expansion of protocol oriented programming that swift has allowed, the lack of generic protocols has felt noticeably lacking and painful in some cases. I made an in depth proposal here: https://github.com/tal/swift-evolution/blob/tal/generic-protocol-proposal/proposals/NNNN-add-generic-protocols.md <https://github.com/tal/swift-evolution/blob/tal/generic-protocol-proposal/proposals/NNNN-add-generic-protocols.md>
> But the tl;dr is this:
> protocol Validator<TypeToValidate> {
>   var value: TypeToValidate { get set }
>   var valueIfValid: TypeToValidate? { get }
> }
> struct FooStringValidator: Validator<String> {
>   //... implementation
> }
> let stringValidator: Validator<String>

The lack of protocol type erasure when associated types are involved is definitely a big problem, and one we'd like to address. However, I don't think moving wholesale to modeling associated types this way is feasible. Many of the standard library protocols have a lot of associated types. 'CollectionType' for instance has its 'Index' type while also inheriting a 'Generator' from SequenceType, and neither of these is what you typically want to parameterize a collection on—you'd want 'CollectionType<Int>' ideally to refer to a collection whose *Element* is Int without having to fully specify the generator and index if you don't care about them. Swift's protocols also support type system features that make some erased protocol types not actual models of their own protocols; `Equatable` is notorious for this, since a type being `Equatable` to its own values does not mean it can be equated to arbitrary other types; `1 == "1"` is nonsense for instance. We have a number of issues that need to be considered here; don't worry, we are considering them!

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20151203/f5e92e56/attachment-0001.html>

More information about the swift-evolution mailing list