是否有一种方法可以在swift中打印变量的运行时类型?例如:

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

在上面的例子中,我正在寻找一种方法来显示变量“soon”的类型是ImplicitlyUnwrappedOptional<NSDate>,或至少NSDate!


当前回答

我的运气是:

let className = NSStringFromClass(obj.dynamicType)

其他回答

你可以使用reflect来获取关于对象的信息。 例如对象类的名称:

var classname = reflect(now).summary

Swift 3.0, Xcode 8

使用下面的代码,您可以向实例请求其类。你也可以比较两个实例,是否具有相同的类。

// 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")
}

在lldb beta 5中,你可以通过以下命令查看对象的类:

fr v -d r shipDate

输出如下:

(DBSalesOrderShipDate_DBSalesOrderShipDate_ *) shipDate = 0x7f859940

展开的命令是这样的:

帧变量(打印帧变量)-d run_target(展开动态类型)

需要知道的一点是,使用“Frame Variable”来输出变量值可以确保不执行任何代码。

这在检查一个对象是否是类的类型时也很方便:

if someObject is SomeClass {
    //someObject is a type of SomeClass
}

请看看下面的代码片段,让我知道你是否在寻找下面这样的东西。

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

var nowDataType = Mirror(reflecting: now)
print("Now is of type: \(nowDataType.subjectType)")

var soonDataType = Mirror(reflecting: soon)
print("Soon is of type: \(soonDataType.subjectType)")