Wednesday, February 28, 2018

Swift Protocols Wish List

Dave DeLong:

If you’re adopting a protocol (especially one from the standard library), the tools don’t provide any help whatsoever in knowing what you actually have to implement.


Basically any time you find yourself using a PAT, you know that you’re either going to have to create a type eraser, or you’re going to have to make things generic that have no business being generic.


I wish the compiler generated type erasers for me.


I wish I could provide default implementations of protocol methods that assign to self.


I wish I could extend a protocol to conform to another protocol.

Previously: Swift Protocols With Associated Types, Swift Type Erasure, Patterns for Working With Associated Types.

Update (2018-03-05): See also: Swift Unwrapped.

Update (2018-07-27): Dave DeLong (tweet):

What I really want to do is this:

protocol Predicate<Element> {
    func contains(_ other: Element) -> Bool
    func union(_ other: Predicate<Element>) -> Predicate<Element>

Of course, the compiler doesn't let me do this.

I want to express the idea that union() can take any Predicate-conforming value with the same element type, and you're going to get back some sort of Predicate-conforming value that contains elements of that type.

Then in specific situations where I can provide a much more efficient implementation (like the IndexSet + IndexSet = IndexSet scenario), I want to provide those explicit overrides for that method, and otherwise default back to the implementations I provide in my protocol extension (which happen to return an OrPredicate<Int>)

Brent Royal-Gordon:

What I think you actually want here is the generalized existential feature. “Generalized existential” is a ten-dollar term for a ten-cent idea: “Swift should have built-in type-erasing wrappers for PATs, much like it has them for ordinary protocols.” Their syntax might be slightly different—they’d probably use a where clause instead of a generic parameter list—but they would do the thing you want to do here.

Comments RSS · Twitter

Leave a Comment