Swift func that takes a Metatype?
ios, swift
Solution
This works:
func funcWithType (type: Any.Type) {
}
funcWithType(String.self)
funcWithType(CGRect.self)
Problem
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!