Constant u16 data

I think it would be a mistake to think about something like constexpr is Swift as just an optimization machinery. Inherently it's a much broader concept. One of the other usecases is Generic value parameters.
If we want to build types representing a constantly sized Vector(or matrix/tensors) its declaration will look something like struct Vector<Element, let Count: Int>, and its usage is like let v: Vector<Int, 42>. The compiler have to transform somehow the literal 42 into something that can be used in generic context and static context. And this is semantically different from optimization.
Ok, we might be able to hardcode this into the compiler for easy types. But how far should we go with this? Should we support Ranges? E.g. should we be able to construct type Clamped<Scalar: Comparable, let Range: ClosedRange<Scalar>>? What if Scalar type is a user defined type?
Another example can be found in this recent thread.
Yet another interesting example is using compile time constants in type contexts which is particularly useful with Union types:

let x: "foo" ∪ "bar"

x is a variable with a type that's isomorphic to Bool, but whose values could be either "foo" or "bar".
This kind of "types" can be used as discriminators when you parse something:

struct Foo: Codable {
  var type: "foo"
  var f: Int
}
struct Bar: Codable {
  var type: "bar"
  var f: Float
}
let fooOrBar = (Foo ∪ Bar).init(from: decoder)
1 Like