Get a type from a class

Is it possible to retrieve data Type

from a class in Swift language

?

This is an example:

class Test : NSObject
{
    let field1 : String
    let field2 : Int

    init(value1 : String, value2 : Int)
    {
        field1 = value1
        field2 = value2
    }
}

let test1 = Test(value1: "Hello", value2: 1)

//this code return the same string with class name (__lldb_expr_129.Test)
let classString = NSStringFromClass(test1.classForCoder) 
let className2 = reflect(test1).summary

//this code return the same ExistentialMetatype value and not the Tes or NSObject type
let classType = reflect(test1).valueType
let classType2 = test1.self.classForCoder

//this return Metatype and not the Test or NSObject type
let classType3 = test1.self.dynamicType

      

Is there a method to retrieve the type Test

and not the value ExistentialMetatype

or Metatype

?

+3


source to share


1 answer


  • .self

    at the facility is pointless. test1.self

    coincides withtest1

  • test1.classForCoder

    is the same as test1.dynamicType

    , which is simple Test.self

    . It is a type (value of the type of a metatype). Swift types do not currently have nice printable representations; but just because it doesn't print well it doesn't mean it's not what you want. Since in this case the type is a class, you can use NSStringFromClass

    or pass it to an object (by providing an object of the Objective-C class) and print it.


+1


source







All Articles