有没有办法快速打印变量的运行时类型?例如:
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!。
ImplicitlyUnwrappedOptional<NSDate>
NSDate!
2016 年 9 月更新
Swift 3.0:使用type(of:), eg type(of: someThing)(因为dynamicType关键字已被删除)
type(of:)
type(of: someThing)
dynamicType
2015 年 10 月更新 :
我将下面的示例更新为新的 Swift 2.0 语法(例如println,被替换为print, toString()is now String())。
println
print
toString()
String()
来自 Xcode 6.3 发行说明 :
在评论中指出Xcode 6.3 发行说明显示了另一种方式:
当与 println 或字符串插值一起使用时,类型值现在打印为完整的解组类型名称。
import Foundation class PureSwiftClass { } var myvar0 = NSString() // Objective-C class var myvar1 = PureSwiftClass() var myvar2 = 42 var myvar3 = "Hans" print( "String(myvar0.dynamicType) -> \(myvar0.dynamicType)") print( "String(myvar1.dynamicType) -> \(myvar1.dynamicType)") print( "String(myvar2.dynamicType) -> \(myvar2.dynamicType)") print( "String(myvar3.dynamicType) -> \(myvar3.dynamicType)") print( "String(Int.self) -> \(Int.self)") print( "String((Int?).self -> \((Int?).self)") print( "String(NSString.self) -> \(NSString.self)") print( "String(Array<String>.self) -> \(Array<String>.self)")
哪个输出:
String(myvar0.dynamicType) -> __NSCFConstantString String(myvar1.dynamicType) -> PureSwiftClass String(myvar2.dynamicType) -> Int String(myvar3.dynamicType) -> String String(Int.self) -> Int String((Int?).self -> Optional<Int> String(NSString.self) -> NSString String(Array<String>.self) -> Array<String>
Xcode 6.3 更新:
您可以使用_stdlib_getDemangledTypeName():
_stdlib_getDemangledTypeName()
print( "TypeName0 = \(_stdlib_getDemangledTypeName(myvar0))") print( "TypeName1 = \(_stdlib_getDemangledTypeName(myvar1))") print( "TypeName2 = \(_stdlib_getDemangledTypeName(myvar2))") print( "TypeName3 = \(_stdlib_getDemangledTypeName(myvar3))")
并将其作为输出:
TypeName0 = NSString TypeName1 = __lldb_expr_26.PureSwiftClass TypeName2 = Swift.Int TypeName3 = Swift.String
原答案:
在 Xcode 6.3 之前,_stdlib_getTypeName获得了变量的重整类型名称。Ewan Swick 的博客条目有助于破译这些字符串:
_stdlib_getTypeName
eg_TtSi代表 Swift 的内部Int类型。
_TtSi
Int
Mike Ash 有一篇很棒的博客文章,涵盖了相同的主题。