2014-09-29 107 views
3

是否可能从Swift language的类中检索数据Type从类中获取类型

这是一个例子:

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 

是否有以检索所述Test类型,而不是ExistentialMetatypeMetatype值的方法?

+0

可能重复[如何在Swift中打印变量的类型或类?](http://stackoverflow.com/questions/24006165/how-do-i-print-the-type-or快速变化的类) – 2014-09-29 14:10:57

回答

1
  1. .self对象是毫无意义的。 test1.selftest1相同
  2. test1.classForCodertest1.dynamicType相同,它只是Test.self。这是一个类型(元类型的值)。 Swift类型目前没有很好的可打印表示;但仅仅因为它不打印漂亮并不意味着它不是你想要的。因为在这种情况下类型是一个类,所以你可以使用NSStringFromClass或将它转换为一个对象(给你Objective-C类对象)并打印它。
+0

我想知道是否有一种方法'objcet.getType()'就像在C# – PizzaRings 2014-09-30 10:18:04

+0

@PizzaRings他给了你,**你不需要一种方法**。你甚至读过(2.)。你想要的类型是* Test.self。 – Binarian 2014-09-30 12:39:57

+0

@PizzaRings:是的。 'object.dynamicType'为你提供了类型。没有什么问题。打印时它看起来不像任何东西。 – newacct 2014-09-30 18:21:06