3

Is it possibile to retrive the 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 retrive the Test type and not the ExistentialMetatype or Metatypevalue ?

Antoine Subit
  • 9,803
  • 4
  • 36
  • 52
PizzaRings
  • 171
  • 1
  • 1
  • 8
  • possible duplicate of [How do I print the type or class of a variable in Swift?](http://stackoverflow.com/questions/24006165/how-do-i-print-the-type-or-class-of-a-variable-in-swift) – Tom Erik Støwer Sep 29 '14 at 14:10

1 Answers1

1
  1. .self on an object is pointless. test1.self is the same as test1
  2. test1.classForCoder is the same as test1.dynamicType which is just Test.self. This is a type (a value of metatype type). Swift types currently do not have nice printable representations; but just because it doesn't print nice does not mean it's not what you want. Since in this case the type is a class, you can use NSStringFromClass or cast it to an object (giving you the Objective-C class object) and print that.
newacct
  • 119,665
  • 29
  • 163
  • 224
  • I was wondering if there is a method `objcet.getType()` like in C# – PizzaRings Sep 30 '14 at 10:18
  • @PizzaRings He gave it to you, **you don't need a method**. Did you even read (2.). You wanted the *type of the class* that is `Test.self`. – Binarian Sep 30 '14 at 12:39
  • @PizzaRings: Yes. `object.dynamicType` gives you the type. There is nothing wrong with it. It just doesn't look like anything when you print it. – newacct Sep 30 '14 at 18:21