¿Cómo puedo imprimir el tipo o clase de una variable en Swift?


¿Hay alguna forma de imprimir el tipo de tiempo de ejecución de una variable en swift? Por ejemplo:

var now = NSDate()
var soon = now.dateByAddingTimeInterval(5.0)

println("\(now.dynamicType)") 
// Prints "(Metatype)"

println("\(now.dynamicType.description()")
// Prints "__NSDate" since objective-c Class objects have a "description" selector

println("\(soon.dynamicType.description()")
// Compile-time error since ImplicitlyUnwrappedOptional<NSDate> has no "description" method

En el ejemplo anterior, estoy buscando una manera de mostrar que la variable "soon" es de tipo ImplicitlyUnwrappedOptional<NSDate>, o al menos NSDate!.

 299
Author: emlai, 2014-06-03

30 answers

Actualización de septiembre de 2016

Swift 3.0: Use type(of:), por ejemplo type(of: someThing) (ya que se ha eliminado la palabra clave dynamicType)

Actualización de Octubre 2015:

Actualizé los ejemplos a continuación a la nueva sintaxis Swift 2.0 (por ejemplo, println se reemplazó con print, toString() es ahora String()).

De las notas de la versión de Xcode 6.3 :

@nschum señala en los comentarios que las notas de la versión de Xcode 6.3 muestran otra forma:

Los valores de tipo ahora se imprimen como el nombre de tipo demangled completo cuando se usan con println o interpolación de cadena.

import Foundation

class PureSwiftClass { }

var myvar0 = NSString() // Objective-C class
var myvar1 = PureSwiftClass()
var myvar2 = 42
var myvar3 = "Hans"

print( "String(myvar0.dynamicType) -> \(myvar0.dynamicType)")
print( "String(myvar1.dynamicType) -> \(myvar1.dynamicType)")
print( "String(myvar2.dynamicType) -> \(myvar2.dynamicType)")
print( "String(myvar3.dynamicType) -> \(myvar3.dynamicType)")

print( "String(Int.self)           -> \(Int.self)")
print( "String((Int?).self         -> \((Int?).self)")
print( "String(NSString.self)      -> \(NSString.self)")
print( "String(Array<String>.self) -> \(Array<String>.self)")

Que produce:

String(myvar0.dynamicType) -> __NSCFConstantString
String(myvar1.dynamicType) -> PureSwiftClass
String(myvar2.dynamicType) -> Int
String(myvar3.dynamicType) -> String
String(Int.self)           -> Int
String((Int?).self         -> Optional<Int>
String(NSString.self)      -> NSString
String(Array<String>.self) -> Array<String>

Actualización para Xcode 6.3:

Puedes usar el _stdlib_getDemangledTypeName():

print( "TypeName0 = \(_stdlib_getDemangledTypeName(myvar0))")
print( "TypeName1 = \(_stdlib_getDemangledTypeName(myvar1))")
print( "TypeName2 = \(_stdlib_getDemangledTypeName(myvar2))")
print( "TypeName3 = \(_stdlib_getDemangledTypeName(myvar3))")

Y obtener esto como salida:

TypeName0 = NSString
TypeName1 = __lldb_expr_26.PureSwiftClass
TypeName2 = Swift.Int
TypeName3 = Swift.String

Respuesta original:

Antes de Xcode 6.3 _stdlib_getTypeName obtuvo el nombre de tipo destrozado de una variable. La entrada de blog de Ewan Swick ayuda a descifrar estas cadenas:

Por ejemplo, _TtSi significa el tipo interno Int de Swift.

Mike Ash tiene una gran entrada de blog que cubre el mismo tema .

 334
Author: Klaas,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-12-18 19:15:42

Editar: Se ha introducido una nueva función toString en Swift 1.2 (Xcode 6.3).

Ahora puede imprimir el tipo demangled de cualquier tipo usando .self y cualquier instancia usando .dynamicType:

struct Box<T> {}

toString("foo".dynamicType)            // Swift.String
toString([1, 23, 456].dynamicType)     // Swift.Array<Swift.Int>
toString((7 as NSNumber).dynamicType)  // __NSCFNumber

toString((Bool?).self)                 // Swift.Optional<Swift.Bool>
toString(Box<SinkOf<Character>>.self)  // __lldb_expr_1.Box<Swift.SinkOf<Swift.Character>>
toString(NSStream.self)                // NSStream

Intenta llamar a YourClass.self y yourObject.dynamicType.

Referencia: https://devforums.apple.com/thread/227425.

 45
Author: akashivskyy,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-04-22 22:43:35

¿Es esto lo que estás buscando?

println("\(object_getClassName(now))");

Imprime "_ _ NSDate "

ACTUALIZACIÓN : Tenga en cuenta que esto ya no parece funcionar a partir de Beta05

 30
Author: Haiku Oezu,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-08-20 11:36:27

Swift 3.0

let string = "Hello"
let stringArray = ["one", "two"]
let dictionary = ["key": 2]

print(type(of: string)) // "String"

// Get type name as a string
String(describing: type(of: string)) // "String"
String(describing: type(of: stringArray)) // "Array<String>"
String(describing: type(of: dictionary)) // "Dictionary<String, Int>"

// Get full type as a string
String(reflecting: type(of: string)) // "Swift.String"
String(reflecting: type(of: stringArray)) // "Swift.Array<Swift.String>"
String(reflecting: type(of: dictionary)) // "Swift.Dictionary<Swift.String, Swift.Int>"
 27
Author: Evgenii,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-01-16 06:11:03

Mi Xcode actual es la versión 6.0 (6A280e).

import Foundation

class Person { var name: String; init(name: String) { self.name = name }}
class Patient: Person {}
class Doctor: Person {}

var variables:[Any] = [
    5,
    7.5,
    true,
    "maple",
    Person(name:"Sarah"),
    Patient(name:"Pat"),
    Doctor(name:"Sandy")
]

for variable in variables {
    let typeLongName = _stdlib_getDemangledTypeName(variable)
    let tokens = split(typeLongName, { $0 == "." })
    if let typeName = tokens.last {
        println("Variable \(variable) is of Type \(typeName).")
    }
}

Salida:

Variable 5 is of Type Int.
Variable 7.5 is of Type Double.
Variable true is of Type Bool.
Variable maple is of Type String.
Variable Swift001.Person is of Type Person.
Variable Swift001.Patient is of Type Patient.
Variable Swift001.Doctor is of Type Doctor.
 23
Author: Matt Hagen,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-09-08 17:45:01

A partir de Xcode 6.3 con Swift 1.2, simplemente puede convertir los valores de tipo en el completo demangled String.

toString(Int)                   // "Swift.Int"
toString(Int.Type)              // "Swift.Int.Type"
toString((10).dynamicType)      // "Swift.Int"
println(Bool.self)              // "Swift.Bool"
println([UTF8].self)            // "Swift.Array<Swift.UTF8>"
println((Int, String).self)     // "(Swift.Int, Swift.String)"
println((String?()).dynamicType)// "Swift.Optional<Swift.String>"
println(NSDate)                 // "NSDate"
println(NSDate.Type)            // "NSDate.Type"
println(WKWebView)              // "WKWebView"
toString(MyClass)               // "[Module Name].MyClass"
toString(MyClass().dynamicType) // "[Module Name].MyClass"
 18
Author: kiding,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-02-10 05:42:36

Todavía se puede acceder a la clase, a través de className (que devuelve un String).

En realidad hay varias maneras de obtener la clase, por ejemplo classForArchiver, classForCoder, classForKeyedArchiver (all return AnyClass!).

No se puede obtener el tipo de un primitivo (un primitivo es no una clase).

Ejemplo:

var ivar = [:]
ivar.className // __NSDictionaryI

var i = 1
i.className // error: 'Int' does not have a member named 'className'

Si quieres obtener el tipo de una primitiva, tienes que usar bridgeToObjectiveC(). Ejemplo:

var i = 1
i.bridgeToObjectiveC().className // __NSCFNumber
 17
Author: Leandros,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-06-03 02:35:59

Puede usar reflect para obtener información sobre object.
Por ejemplo nombre de la clase de objeto:

var classname = reflect(now).summary
 16
Author: Stan,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-08-15 12:27:53

Tuve suerte con:

let className = NSStringFromClass(obj.dynamicType)
 13
Author: mxcl,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-09-07 20:58:30

Xcode 8 Swift 3.0 use type (of:)

let className = "\(type(of: instance))"
 11
Author: Hari Kunwar,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-09-19 19:10:25

En Xcode 8, Swift 3.0

Pasos:

1. Obtener el Tipo:

Opción 1:

let type : Type = MyClass.self  //Determines Type from Class

Opción 2:

let type : Type = type(of:self) //Determines Type from self

2. Convertir Tipo a Cadena:

let string : String = "\(type)" //String
 10
Author: user1046037,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-10-09 12:24:32

En Swift 3.0, puede usar type(of:), ya que se ha eliminado la palabra clave dynamicType.

 8
Author: BrunoSerrano,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-09-17 06:07:07

SWIFT 3

Con la última versión de Swift 3 podemos obtener bonitas descripciones de nombres de tipos a través del inicializador String. Como, por ejemplo print(String(describing: type(of: object))). Donde object puede ser una variable de instancia como array, un diccionario, un Int, un NSDate, una instancia de una clase personalizada, etc.

Aquí está mi respuesta completa: Obtener el nombre de clase del objeto como cadena en Swift

Esa pregunta está buscando una manera de obtener el nombre de clase de un objeto como cadena pero, también propuse otra forma de obtener el nombre de clase de una variable que no es subclase de NSObject. Aquí está:

class Utility{
    class func classNameAsString(obj: Any) -> String {
        //prints more readable results for dictionaries, arrays, Int, etc
        return String(describing: type(of: obj))
    }
}

Hice una función estática que toma como parámetro un objeto de tipo Any y devuelve su nombre de clase como String:).

Probé esta función con algunas variables como:

    let diccionary: [String: CGFloat] = [:]
    let array: [Int] = []
    let numInt = 9
    let numFloat: CGFloat = 3.0
    let numDouble: Double = 1.0
    let classOne = ClassOne()
    let classTwo: ClassTwo? = ClassTwo()
    let now = NSDate()
    let lbl = UILabel()

Y la salida fue:

  • diccionary es de tipo Dictionary
  • el array es de tipo Array
  • numInt es de tipo Int
  • numFloat es de tipo CGFloat
  • numDouble es de tipo Double
  • ClassOne es de tipo: ClassOne
  • classTwo es de tipo: ClassTwo
  • ahora es de tipo: Fecha
  • lbl es de tipo: UILabel
 6
Author: mauricioconde,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-23 12:10:29

Cuando se usa Cocoa (no CocoaTouch), se puede usar la propiedad className para objetos que son subclases de NSObject.

println(now.className)

Esta propiedad no está disponible para objetos Swift normales, que no son subclases de NSObject (y de hecho, no hay un id raíz ni un tipo de objeto en Swift).

class Person {
    var name: String?
}

var p = Person()
println(person.className) // <- Compiler error

En CocoaTouch, en este momento no hay una manera de obtener una descripción de cadena del tipo de una variable dada. Funcionalidad similar tampoco existe para los tipos primitivos en Cacao o CocoaTouch.

El Swift REPL es capaz de imprimir un resumen de valores incluyendo su tipo, por lo que es posible que esta forma de introspección sea posible a través de una API en el futuro.

EDITAR: dump(object) parece hacer el truco.

 4
Author: Matt Bridges,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-06-19 12:58:01

He intentado algunas de las otras respuestas aquí, pero milage parece muy en lo que el objeto subordinado es.

Sin embargo, encontré una manera de obtener el nombre de clase Object-C para un objeto haciendo lo siguiente:

now?.superclass as AnyObject! //replace now with the object you are trying to get the class name for

Aquí hay un ejemplo de cómo lo usarías:

let now = NSDate()
println("what is this = \(now?.superclass as AnyObject!)")

En este caso se imprimirá NSDate en la consola.

 4
Author: James Jones,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-09-16 01:31:25

Encontré esta solución que con suerte podría funcionar para alguien más. He creado un método de clase para acceder al valor. Tenga en cuenta que esto funcionará solo para la subclase NSObject. Pero al menos es una solución limpia y ordenada.

class var className: String!{
    let classString : String = NSStringFromClass(self.classForCoder())
    return classString.componentsSeparatedByString(".").last;
}
 4
Author: DennyLou,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-02-07 03:20:35

En el último XCode 6.3 con Swift 1.2, esta es la única manera que encontré:

if view.classForCoder.description() == "UISegment" {
    ...
}
 4
Author: Joel Kopelioff,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-04-09 02:07:30

En lldb a partir de la beta 5, se puede ver la clase de un objeto con el comando:

fr v -d r shipDate

Que produce algo como:

(DBSalesOrderShipDate_DBSalesOrderShipDate_ *) shipDate = 0x7f859940

El comando expanded out significa algo así como:

Frame Variable (print a frame variable) -d run_target (expand dynamic types)

Algo útil saber es que el uso de "Variable de marco" para generar valores de variables garantiza que no se ejecute ningún código.

 3
Author: Kendall Helmstetter Gelner,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-08-15 20:41:40

He encontrado una solución para las clases autodesarrolladas (o a las que tenga acceso).

Coloque la siguiente propiedad calculada dentro de su definición de clase de objetos:

var className: String? {
    return __FILE__.lastPathComponent.stringByDeletingPathExtension
}

Ahora simplemente puede llamar el nombre de la clase en su objeto de la siguiente manera:

myObject.className

Tenga en cuenta que esto solo funcionará si su definición de clase está hecha dentro de un archivo que se llama exactamente como la clase de la que desea el nombre.

Ya que esto es comúnmente el caso la respuesta anterior debería hacerlo para la mayoría de los casos. Pero en algunos casos especiales es posible que necesite encontrar una solución diferente.


Si necesita el nombre de la clase dentro de la clase (archivo) en sí simplemente puede usar esta línea:

let className = __FILE__.lastPathComponent.stringByDeletingPathExtension

Tal vez este método ayuda a algunas personas por ahí.

 3
Author: Dschee,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-12-18 00:20:16

Basado en las respuestas y comentarios dados por Klass y Kevin Ballard arriba, yo iría con:

println(_stdlib_getDemangledTypeName(now).componentsSeparatedByString(".").last!)
println(_stdlib_getDemangledTypeName(soon).componentsSeparatedByString(".").last!)
println(_stdlib_getDemangledTypeName(soon?).componentsSeparatedByString(".").last!)
println(_stdlib_getDemangledTypeName(soon!).componentsSeparatedByString(".").last!)

println(_stdlib_getDemangledTypeName(myvar0).componentsSeparatedByString(".").last!)
println(_stdlib_getDemangledTypeName(myvar1).componentsSeparatedByString(".").last!)
println(_stdlib_getDemangledTypeName(myvar2).componentsSeparatedByString(".").last!)
println(_stdlib_getDemangledTypeName(myvar3).componentsSeparatedByString(".").last!)

Que se imprimirá:

"NSDate"
"ImplicitlyUnwrappedOptional"
"Optional"
"NSDate"

"NSString"
"PureSwiftClass"
"Int"
"Double"
 3
Author: Vince O'Sullivan,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-01-01 12:15:43
let i: Int = 20


  func getTypeName(v: Any) -> String {
    let fullName = _stdlib_demangleName(_stdlib_getTypeName(i))
    if let range = fullName.rangeOfString(".") {
        return fullName.substringFromIndex(range.endIndex)
    }
    return fullName
}

println("Var type is \(getTypeName(i)) = \(i)")
 3
Author: Alex Burla,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-01-22 23:18:58

Muchas de las respuestas aquí no funcionan con la última versión de Swift (Xcode 7.1.1 en el momento de escribir este artículo).

La forma actual de obtener la información es crear un Mirror e interrogarlo. Para el nombre de la clase es tan simple como:

let mirror = Mirror(reflecting: instanceToInspect)
let classname:String = mirror.description

También se puede obtener información adicional sobre el objeto desde Mirror. Véase http://swiftdoc.org/v2.1/type/Mirror / para más detalles.

 3
Author: Joseph Lord,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-11-11 17:12:55

La respuesta superior no tiene un ejemplo funcional de la nueva forma de hacer esto usando type(of:. Así que para ayudar a los novatos como yo, aquí hay un ejemplo de trabajo, tomado principalmente de los documentos de Apple aquí - https://developer.apple.com/documentation/swift/2885064-type

doubleNum = 30.1

func printInfo(_ value: Any) {
    let varType = type(of: value)
    print("'\(value)' of type '\(varType)'")
}

printInfo(doubleNum)
//'30.1' of type 'Double'
 3
Author: Joshua Dance,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-09-06 05:17:05

No parece haber una forma genérica de imprimir el nombre del tipo de un valor arbitrario. Como otros han señalado, para las instancias class puede imprimir value.className pero para los valores primitivos parece que en tiempo de ejecución, la información de tipo se ha ido.

Por ejemplo, parece que no hay una manera de escribir: 1.something() y salir Int para cualquier valor de something. (Puedes, como sugirió otra respuesta, usar i.bridgeToObjectiveC().className para darte una pista, pero __NSCFNumber es no en realidad el tipo de i just solo a qué se convertirá cuando cruce el límite de una llamada a una función Objective-C.)

Estaría encantado de que se demuestre que está mal, pero parece que la comprobación de tipos se realiza en tiempo de compilación, y al igual que C++ (con RTTI deshabilitado), gran parte de la información de tipos se ha ido en tiempo de ejecución.

 2
Author: ipmcc,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-06-03 20:03:56

No es exactamente lo que busca, pero también puede verificar el tipo de la variable contra tipos Swift como este:

let object: AnyObject = 1

if object is Int {
}
else if object is String {
}

Por ejemplo.

 1
Author: PersuitOfPerfection,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-04-22 11:59:03

Xcode 7.3.1, Swift 2.2:

String(instanceToPrint.self).componentsSeparatedByString(".").last

 1
Author: leanne,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-06-24 22:24:18

Swift 3.0, Xcode 8

Con el siguiente código puede pedir a una instancia su clase. También puede comparar dos instancias, ya sea que tengan la misma clase.

// CREATE pure SWIFT class
class MySwiftClass {
    var someString : String = "default"
    var someInt    : Int = 5
}

// CREATE instances
let firstInstance = MySwiftClass()
let secondInstance = MySwiftClass()
secondInstance.someString = "Donald"
secondInstance.someInt = 24

// INSPECT instances
if type(of: firstInstance) === MySwiftClass.self {
    print("SUCCESS with ===")
} else {
    print("PROBLEM with ===")
}

if type(of: firstInstance) == MySwiftClass.self {
    print("SUCCESS with ==")
} else {
    print("PROBLEM with ==")
}

// COMPARE CLASS OF TWO INSTANCES
if type(of: firstInstance) === type(of: secondInstance) {
    print("instances have equal class")
} else {
    print("instances have NOT equal class")
}
 1
Author: LukeSideWalker,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-02-14 06:46:31

Swift versión 4:

print("\(type(of: self)) ,\(#function)")
// within a function of a class

Gracias @ Joshua Dance

 1
Author: dengApro,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-04-27 03:15:58

Así es como obtiene una cadena de tipo de su objeto o Tipo que es consistente y tiene en cuenta a qué módulo pertenece la definición de objeto o está anidado. Funciona en Swift 4.x.

@inline(__always) func typeString(for _type: Any.Type) -> String {
    return String(reflecting: type(of: _type))
}

@inline(__always) func typeString(for object: Any) -> String {
    return String(reflecting: type(of: type(of: object)))
}

struct Lol {
    struct Kek {}
}

// if you run this in playground the results will be something like
typeString(for: Lol.self)    //    __lldb_expr_74.Lol.Type
typeString(for: Lol())       //    __lldb_expr_74.Lol.Type
typeString(for: Lol.Kek.self)//    __lldb_expr_74.Lol.Kek.Type
typeString(for: Lol.Kek())   //    __lldb_expr_74.Lol.Kek.Type
 1
Author: Igor Muzyka,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-08-07 22:21:39

Esto también es útil cuando se comprueba si un objeto es un tipo de clase:

if someObject is SomeClass {
    //someObject is a type of SomeClass
}
 0
Author: Nam,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-01-19 10:25:58