[swift-evolution] [Pitch] Refactor Metatypes

Brent Royal-Gordon brent at architechies.com
Fri Sep 30 17:56:05 CDT 2016


> On Sep 29, 2016, at 9:21 PM, Xiaodi Wu <xiaodi.wu at gmail.com> wrote:
> 
> Can you elaborate on your two reasons for the proposed Type<T>?
> 
> In particular, what do you mean by inheritable and non-inheritable members of T? Where do these come into play? How is the current T.Type deficient in this respect?

Consider a snippet of code like this:

	class A { init(a: Int) { } }
	class B: A { init(b: Int) { super.init(a: b) } }

You can call `A.init(a:)` directly:

	A(a: 0)
	A.self.init(a: 0)

However, if you try to assign `A`'s type instance to a variable and do it through there, you can't:

	let aType: A.Type = A.self
	aType.init(a: 0)		// Error: constructing an object of class type 'A' with a metatype value must use a 'required' initializer

This is a reflection of the fact that an `A.Type` could be `A.self` or `B.self` (or any other subclass of `A`), and `B.self` may not have an `init(a:)`.

`Type<A>` does not have this problem because it *is* guaranteed to be an `A`. It can express initializers and potentially anything else we might add that doesn't get inherited.

Of course, that isn't hugely useful right now because `Type<T>` only has one instance, and you can just refer to that instance directly. But I don't like that this distinction is unutterable; `Type<T>` corrects that.

And I think we may have features in the future where this is useful. For instance, if reflection ever gains the ability to access non-stored-property members, the distinction between `Subtype<T>` and `Type<T>` may become important. And if we ever get the ability to conform metatypes to protocols, I think non-inheritable conformances may be a good thing.

> Regarding (2), it is already possible to do precise type matches using `==` instead of `is` (see corelibs-foundation for extensive uses). What does the proposal offer that goes beyond what we currently have?

`as?` compatibility, I suppose? Honestly, that's just something I noticed when I was writing it up. It might not be important.

-- 
Brent Royal-Gordon
Architechies



More information about the swift-evolution mailing list