SE-0244: Opaque Result Types

Exactly this duality tells me we need to design a counterpart to generics. I don't know if there is an existing term for that. Perhaps 'reverse generics'? I wil use this term for the rest of this post. Please correct me if that doesn't make any sense.

Refining my earlier idea a little bit, using the ^ in the generic parameter list to designate reverse generic parameters:

func useFoo<F: Foo>(_ foo: F) { /* ... */ }
func makeFoo<^F: Foo>() -> F { /* ... */ }

So, to be clear:

  • Normal generic type parameters are made concrete by the caller.
  • Reverse generic type parameters (prefixed ^) are made concrete by the callee.

Type inference will most of the time do its job, but explicitly typing something as the reverse generic type parameter of makeFoo() could perhaps be done as follows:

// Explicitly typing a variable with the return type of makeFoo():
var myFoo: makeFoo.F = makeFoo()

// Explicitly typing an array of the type returned by makeFoo():
var myFooArray = [makeFoo.F]()
myFooArray.append(makeFoo())

This notation also makes it possible to constrain functions to return the same concrete type, which could make @Vogel happy:

// Returns an opaque collection
func makeCollection<T, ^C: Collection>(with element: T) -> C where C.Element == T {
  return [element]
}

// Returns the same type opaque collection, with Element == String
func makeCollectionWithString<^C>() -> C where C == makeCollection.C, C.Element == String {
  return makeCollection(with: "Foo")
}

// The following will type check correctly:
var myCollection = makeCollectionWithString() + makeCollection(with: "Bar")
print(myCollection) // ["Foo", "Bar"]

Using this notation there is no need for a keyword like 'opaque' or 'some'. I see that @beccadax posted a similar idea in the Protocol<.AssocType == T>... thread and he notes that 'some' could be used as shorthand syntax. In my opinion the following would be the right course of action:

  1. Decide on the basic design for a 'reverse generics' system.
  2. See how ergonomics can be improved with additional shorthand syntax (if there is a need for it).

I think this will provide a better foundation for future directions.

I'm no language expert, so if I said anything that makes no sense or if I butchered any terminology, please let me know.