是否有一种方法可以在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!


当前回答

Xcode 8 Swift 3.0使用类型:

let className = "\(type(of: instance))"

其他回答

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

fr v -d r shipDate

输出如下:

(DBSalesOrderShipDate_DBSalesOrderShipDate_ *) shipDate = 0x7f859940

展开的命令是这样的:

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

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

Xcode 8 Swift 3.0使用类型:

let className = "\(type(of: instance))"

根据上面Klass和Kevin Ballard给出的答案和评论,我认为:

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!)

这将打印出:

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

"NSString"
"PureSwiftClass"
"Int"
"Double"

在最新的XCode 6.3和Swift 1.2中,这是我发现的唯一方法:

if view.classForCoder.description() == "UISegment" {
    ...
}

我为自己开发的类(或您可以访问的类)找到了一个解决方案。

在你的对象类定义中放置以下计算属性:

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

现在你可以像这样简单地调用对象的类名:

myObject.className

请注意,只有当类定义是在与您想要的类名称完全相同的文件中创建时,这才会起作用。

因为这是常见的情况,上面的答案应该做的大多数情况下。但在某些特殊情况下,你可能需要想出一个不同的解决方案。


如果你需要类(文件)本身的类名,你可以简单地使用这一行:

let className = __FILE__.lastPathComponent.stringByDeletingPathExtension

也许这个方法能帮助到一些人。