[swift-evolution] [swift-evolution-announce] [Review] SE-0089: Replace protocol<P1, P2> syntax with Any<P1, P2>

Brent Royal-Gordon brent at architechies.com
Wed May 25 02:45:11 CDT 2016

> - A few people have also noted the similarity between Any<...> and normal generic types. This is potentially confusing today, but with enough magic language features from the future, Any *could* conceivably be made a library feature in the fullness of time:
> 	// Let's say 'protocol' constraints indicate second-order constraint variables:
> 	enum Any<Constraints: protocol> {
> 		// And we have GADTs:
> 		case value<T: Constraints>(T)
> 	}
> 	// And we have user-defined value subtyping:
> 	extension <Constraints: protocol, T: Constraints> T: Any<Constraints> { ... }

I wanted to reply to this, because this is a beautiful dream, but if we want to treat `Any` like some kind of magical variadic generic type, that has some interesting implications for its design right now.

1) In a normal generic type, when you leave out the generic parameters, Swift infers them. (Think of casting an array literal to `Array`, which pins down the collection type but not the elements.) If `Any` were handled similarly, that would mean that `foo as Any` would not necessarily have an empty set of constraints, but would rather have an *inferred* set of constraints. If you wanted to force it to have no constraints, you would need to write `Any<>`. 

2) We would not normally expect to be able to cast between a normal generic type and the instance contained in it. Instead, we would expect to use initializers, just as we're now planning to require for Objective-C bridging:

	let myExistentialInteger = Any<Integer>(myInt)
	let myInt2 = Int(any: myExistentialInteger)!

Note that, if we were passing to an API which specifically expected an `Any<Integer>`, we could just write `Any(myInt)` and type inference would figure out the rest.

Brent Royal-Gordon

More information about the swift-evolution mailing list