Swift Proposal: Integer Generic Parameters
SE-0452 (via Steve Canon):
Swift does not currently support fixed-size or fixed-capacity collections with inline storage. (Or at least, it doesn’t do so well, not without forming a struct with some specific number of elements and doing horrible things with
withUnsafePointer
to handle indexing.) Most of the implementation of something like a fixed-size array, or a fixed-capacity growable array with a maximum size, or a hash table with a fixed number of buckets, is agnostic to any specific size or capacity, so that implementation would ideally be generic over size so that a library implementation can be reused for any given size.Beyond inline storage sizes, there are other use cases for carrying integers in type information, such as to represent an operation with a particular input or output size. Carrying this information in types can allow for APIs with stronger static guarantees that chains of operations match in the number of elements they consume or produce.
[…]
Generic types can now be parameterized by integer parameters, declared using the syntax
let <Name>: Int
inside of the generic parameter angle brackets:struct Vector<let count: Int, Element> { /*implementation TBD*/ }[…]
On platforms where the vendor ships the Swift runtime with the operating system, there may be limitations on using integer generic parameters in programs that want to target earlier versions of those platforms that don’t have the necessary runtime support.
The Future directions section is interesting.
Previously:
- Open Sourcing NonEmpty
- Swift Imports Fixed-size C Arrays As Tuples
- Why Dependent Types Matter
- Types in Microsoft Office