swiftreflectionmetatype

Getting Type identity of Swift type by name


I'm trying to use a type identity as a key in a dictionary, but I'm having trouble writing the declaration. In C#, I would use something like this:

Type theType = typeof(MyCoolClass);

It seems like in Swift I want to use type(of:) - according to the docs, this function returns a Metaclass object, but when I try to use this type, I get:

Type Metatype not found

protocol DependencyResolver {
     func getObject<T>(type: Metatype, contract: String?) -> T?
     func getAllObjects<T>(type: Metatype, contract: String?) -> T?
}

Solution

  • The Metatype is actually a generic argument of the type(of:) function (i.e., not a nominal type). The dynamic type returned is a concrete metatype (T.Type).

    For instance, try using Any.Type instead ;)