Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift func that takes a Metatype?

Tags:

ios

swift

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!

like image 587
aleclarson Avatar asked Jul 08 '14 23:07

aleclarson


People also ask

What is Metatype in Swift?

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 .

What is type () in Swift?

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.

What is .self and .type in Swift?

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.

What is metatype?

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.


1 Answers

This works:

func funcWithType (type: Any.Type) {
}

funcWithType(String.self)
funcWithType(CGRect.self)
like image 68
newacct Avatar answered Sep 23 '22 01:09

newacct