[swift-evolution] [Pitch] Extend Any.Type to allow construction of bound generic types
Joanna Carter
joanna at carterconsulting.org.uk
Wed Apr 20 10:36:48 CDT 2016
Hi Doug
> In programming-language circles, this feature is called “dependent types” (see, e.g., https://en.wikipedia.org/wiki/Dependent_type), and it introduces significant complicates into a type system. For example, determining whether two types are equivalent becomes a run-time property rather than a compile-time property. I don’t know if Swift will end with a dependently-typed type system. To get there, we would need a number of very strongly-motivating use cases illustrating how common programming tasks can be improved with dependent types, and we would need to solid plan for managing the complexity—both implementation complexity in the compiler’s type checker and also the language complexity seen by Swift user’s when they encounter this feature.
I must admit to being ever so slightly confused about your connection with "dependent types"; in all my years of programming, I have never come across the context of the expression as found in the article cited. Anything that needs algebraic formulae to explain is far too complicated for mere mortal programmers and I am willing to state that I certainly didn't understand more than a few words.
All I am postulating is the ability to create instances of generic types, bound to (a) parameter type(s) in the same manner as is currently possible with non-generic types.
To bring it down to basics, take the example of wanting to create an array of a given type of objects:
let aType: Any.Type = Int.self
var arr = [aType]
… creates an array of Any.type…
let aType: Any.Type = Int.self
var arr = [aType]()
… results in an error "Invalid use of '()' to call a value of non-function type '[Any.Type]'"
let aType: Any.Type = Int.self
var arr = Array<aType>()
… results in an error "'aType' is not a type"
So, how are we meant to be able to create arrays, or any other generic type that require to be bound to a type known only at runtime?
In C#, We have the Type class, which contains useful properties like isGenericType, isConstructedGenericType and methods like GetGenericArguments() and, most important to this use case, MakeGenericType(Type []).
I would make a strong argument for completing Swift generics by including such facilities in Any.Type, so that:
1. we do not have to use the somewhat cumbersome Mirror mechanism
2. we can do something useful with instances of Any.Type, which, at present, does absolutely nothing.
Adding similar functionality to C#'s Type class to Any.Type would break absolutely zero code but would make life a whole load easier for those of us who are power users of generics. Otherwise, FMPOV, Swift generics are but a pale imitation of the concept and very much second class citizens in the language.
Joanna
--
Joanna Carter
Carter Consulting
More information about the swift-evolution
mailing list