What is the point of metatypes in swift?

At this point I just scoring poor sides of swift.

As you all know, swift allows to express (to some extent) types as value, which are called metatypes (ex String.self etc). But the thing is, you cannot do anything with it:

let type = String.self
let anotherType = Optional<type>.self //error: use of undeclared type 'type'

Nither you can partially specialize them.

var type = Dictionary<String, _>.self
type.Value = Bool.random() ? String.self : Int.self

So what do you all do with them, if anything?
By the way, if types as values facility is to be expanded, should this mean that there should also be values as types? :thinking:
Things like typealias Zero<N: Numeric> = N.init(exactly: 0) would be nice to have.

Hi @total_swiftification, you can:

typealias IntArray = Array<Int>

let A: IntArray = [1,2,3]
print(A, type(of: A))

typealias MyType<Value> = Dictionary<String, Value>

let B: MyType<Double> = ["one": 1.0, "two": 2.0, "three": 3.0]
print(B, type(of: B))

Nah, thats different

Metatypes are usually used to aid type inference or enforce the type. You can see in the SingleValueDecodingContainer that there are many functions of signature:

func decode(_ type: Int32.Type) throws -> Int32

So when you want to invoke it, you need to do decoder.decode(Int32.self).

Another, less common usage is to access the static functions for protocol conformance:

protocol Test {
    static func foo() -> Int
extension Int: Test {
    static func foo() -> Int { 15 }

var a: Test.Type = Int.self
a.foo() // 15

You seem to hold a very loose distinction of types and instances.
You could create a generic type:

typealias Zero<N: Numeric> = SomeWrapper<N>

or you can create a generic function that returns an instance of that type:

func zero<N: Numeric>(of _: N.Type) -> N { 0 }

That... doesn't sound quite right in a strongly-typed language. Are you trying to achieve some behaviour? It's probably more appropriate (for lack of a better word) to using enum or [String: Any].

1 Like

Nope, I was referring to type' rank. See if we assume that a any type is actually a set of predicates over some set of values, than it should be possible to construct a type that has a defining signature (for all x, x is equal to 0, for example). This would be rank 0 type.
Maybe this would make it more apparent
typealias IZero = 0, yes it is a type with single possible value. Void is of that kind.


Not exactly a specific one, but this opens a road to a thing called type level computations, which would be fancy and very expressive.

I have seen that a lot of people want generalized existential, and this would be a natural addition to it.

Probably complete specialization would be a necessity, enforced by a compiler. (Attempt to instantiate from incomplete type should be an error)