有没有办法在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!。
2016年9月更新
原文链接:https://www.f2er.com/swift/322061.htmlSwift 3.0:使用类型(of :),例如type(of:someThing)(因为dynamicType关键字已被删除)
2015年10月更新:
我更新了下面的例子到新的Swift 2.0语法(例如println被替换为print,toString()现在是String())。
从Xcode 6.3发行说明:
@nschum指出在Xcode 6.3 release notes显示另一种方式的意见:
Type values now print as the full demangled type name when used with
println or string interpolation.
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():
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’s blog entry帮助解密这些字符串:
例如_TtSi代表Swift的内部Int类型。