有没有一种方法可以快速打印变量的运行时类型?例如:
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:),例如type(of: someThing)(因为dynamicType关键字已删除)
type(of:)
type(of: someThing)
dynamicType
2015年10月更新 :
我将下面的示例更新为新的Swift 2.0语法(例如,println已被替换为print,toString()现在是String())。
println
print
toString()
String()
从Xcode 6.3发行说明 :
@nschum在注释中指出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
例如_TtSi代表Swift的内部Int类型。
_TtSi
Int
迈克·阿什(Mike Ash)在同一个主题的博客文章中非常出色。