type

func type<Type, Metatype>(_: Type)

Returns the dynamic type of a value.

of: The value to take the dynamic type of. Returns: The dynamic type, which will be a value of metatype type.

Remark: If the parameter is statically of a protocol or protocol composition type, the result will be an existential metatype (P.Type for a protocol P), and will represent the type of the value inside the existential container with the same protocol conformances as the value. Otherwise, the result will be a concrete metatype (T.Type for a non-protocol type T, or P.Protocol for a protocol P). Normally, this will do what you mean, but one wart to be aware of is when you use type(of:) in a generic context with a type parameter bound to a protocol type:

func foo<T>(x: T) -> T.Type { return type(of: x) } protocol P {} func bar(x: P) { foo(x: x) // Call foo with T == P }

since the call to type(of:) inside foo only sees T as a concrete type, foo will end up returning P.self instead of the dynamic type inside x. This can be worked around by writing type(of: x as Any) to get the dynamic type inside x as an Any.Type.

Declaration

func type<Type, Metatype>(of: Type) -> Metatype