As Apple says in the Metatype Type section in Swift's docs:
A metatype type refers to the type of any type, including class types, structure types, enumeration types, and protocol types.
Is there a base class to refer to any class, struct, enum, or protocol (eg MetaType)?
My understanding is that protocol types are limited to use as a generic constraint, because of Self or associated type requirements (well, this is what an Xcode error was telling me).
So, with that in mind, maybe there is a Class base class for identifying class references? Or a Type base class for all constructable types (class, struct, enum)? Other possibilities could be Protocol, Struct, Enum, and Closure.
See this example if you don't get what I mean yet.
func funcWithType (type: Type) {
// I could store this Type reference in an ivar,
// as an associated type on a per-instance level.
// (if this func was in a class, of course)
self.instanceType = type
}
funcWithType(String.self)
funcWithType(CGRect.self)
While generics work great with 1-2 constant associated types, I wouldn't mind being able to treat associated types as instance variables.
Thanks for any advice!
A metatype type refers to the type of any type, including class types, structure types, enumeration types, and protocol types. The metatype of a class, structure, or enumeration type is the name of that type followed by .
Type casting is a way to check the type of an instance, or to treat that instance as a different superclass or subclass from somewhere else in its own class hierarchy. Type casting in Swift is implemented with the is and as operators.
From the Swift Programming Language Book: The Self type isn't a specific type, but rather lets you conveniently refer to the current type without repeating or knowing that type's name. In a protocol declaration or a protocol member declaration, the Self type refers to the eventual type that conforms to the protocol.
metatype (plural metatypes) (biology) A topotype of a species which is confirmed as belonging to that species by the author who originally described it. (programming) The type of a type.
This works:
func funcWithType (type: Any.Type) {
}
funcWithType(String.self)
funcWithType(CGRect.self)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With