[Pitch] Opaque Conformance for Protocols

This sounds similar to what I talked about here, and I hope I didn't unduly tie it to type disjunctions because it's really a distinct feature that has merit on its own even if type disjunctions are never supported.

What makes a closed protocol (that seems like that most natural syntax to me as the corollary to an open class) really useful in my opinion is not just preventing outside conformances (that is helpful though) but that closing it means the compiler knows the full list of conforming types when it compiles the protocol's module, which means it can support exhaustive switching:

closed protocol P {}

struct P1: P {}
struct P2: P {}
enum P3: P {}

let aP: any P = getAP()

switch aP {
  case let p1 as P1: ...
  case let p2 as P2: ...
  case let p3 as P3: ...
  // No open-ended default
}

I think this is a really important feature for Swift to gain because without it developers reach for enums too frequently, which is a problem because they aren't strongly typed (I can't write a function that requires a specific case of an enum) and don't support arbitrary overlapping hierarchies (hence the Russian doll nesting of subcodes in errors which would be more elegantly expressible as refined protocols). But the alternative, strongly typed option of protocols with concrete conformances can't be exhaustively switched on without introducing an enum as a manual type eraser, which reintroduces the problem that it can't model overlapping hierarchies properly.

2 Likes