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


当前回答

似乎没有通用的方法来打印任意值的类型的类型名。正如其他人所注意到的,对于类实例,可以打印值。但是对于基本值,在运行时,类型信息消失了。

例如,似乎没有一种方法可以输入:1.something()并得到Int的任何值。(正如另一个答案所建议的那样,您可以使用i. bridgetooobjecvec()。__NSCFNumber实际上并不是i的类型——只是当它越过Objective-C函数调用的边界时它将被转换为的类型。)

我很乐意被证明是错的,但看起来类型检查都是在编译时完成的,而且像c++(禁用RTTI)一样,很多类型信息在运行时就消失了。

其他回答

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

var classname = reflect(now).summary

编辑:在Swift 1.2 (Xcode 6.3)中引入了一个新的toString函数。

你现在可以使用.self和使用.dynamicType打印任意类型的需求类型:

struct Box<T> {}

toString("foo".dynamicType)            // Swift.String
toString([1, 23, 456].dynamicType)     // Swift.Array<Swift.Int>
toString((7 as NSNumber).dynamicType)  // __NSCFNumber

toString((Bool?).self)                 // Swift.Optional<Swift.Bool>
toString(Box<SinkOf<Character>>.self)  // __lldb_expr_1.Box<Swift.SinkOf<Swift.Character>>
toString(NSStream.self)                // NSStream

试着调用你的类。self和youobject . dynamictype。

参考:https://devforums.apple.com/thread/227425。

根据上面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"

我在这里尝试了一些其他的答案,但milage似乎很清楚下面的对象是什么。

然而,我确实发现了一种方法,你可以通过以下方式获得对象的object - c类名:

now?.superclass as AnyObject! //replace now with the object you are trying to get the class name for

下面是一个如何使用它的例子:

let now = NSDate()
println("what is this = \(now?.superclass as AnyObject!)")

在本例中,它将在控制台中打印NSDate。

在Swift 3.0中,你可以使用type(of:),因为dynamicType关键字已被删除。