Fast function using metatype?

As Apple says in the Metatype Type section of Swift docs:

A metatype type refers to a type of any type, including class types, structure types, enumeration types, and protocol types.

Is there a base class for referencing any class, structure, enumeration or protocol (e.g. MetaType )?

My understanding is that protocol types are limited to being used as a general restriction due to proprietary or related type requirements (well, this is what the Xcode error told me).

So, keeping in mind, perhaps there is a base class, Class, for defining class references? Or is the base class Type for all constructive types (class, structure, enumeration)? Other features may include Protocol , Struct , Enum, and Closure .

See this example if you have not yet understood what I mean.

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 fine with 1-2 constant bound types, I would not mind treating bound types as instance variables.

Thanks for any advice!

+8
ios swift
source share
2 answers

It works:

 func funcWithType (type: Any.Type) { } funcWithType(String.self) funcWithType(CGRect.self) 
+11
source share

In your example, the implementation will be as follows:

 // protocol that requires an initializer so you can later call init from the type protocol Initializeable { init() } func funcWithType (type: Initializeable.Type) { // make a new instance of the type let instanceType = type() // in Swift 2 you have to explicitly call the initializer: let instanceType = type.init() // in addition you can call any static method or variable of the type (in this case nothing because Initializeable doesn't declare any) } // make String and CGRect conform to the protocol extension String: Initializeable {} extension CGRect: Initializeable {} funcWithType(String.self) funcWithType(CGRect.self) 
+3
source share

All Articles