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


当前回答

我找到了这个解决方案,希望对其他人也有用。 我创建了一个类方法来访问该值。请记住,这只适用于NSObject子类。但至少是一个干净整洁的解决方案。

class var className: String!{
    let classString : String = NSStringFromClass(self.classForCoder())
    return classString.componentsSeparatedByString(".").last;
}

其他回答

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

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

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

当使用Cocoa(而不是CocoaTouch)时,你可以为NSObject的子类对象使用className属性。

println(now.className)

这个属性对于普通的Swift对象是不可用的,它不是NSObject的子类(事实上,在Swift中没有根id或对象类型)。

class Person {
    var name: String?
}

var p = Person()
println(person.className) // <- Compiler error

在CocoaTouch中,此时没有办法获得给定变量类型的字符串描述。类似的功能在Cocoa或CocoaTouch中也不存在。

Swift REPL能够打印出值的摘要,包括它的类型,所以这种内省方式可能在未来通过API实现。

编辑:转储(对象)似乎做的把戏。

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

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

斯威夫特4:

// "TypeName"
func stringType(of some: Any) -> String {
    let string = (some is Any.Type) ? String(describing: some) : String(describing: type(of: some))
    return string
}

// "ModuleName.TypeName"
func fullStringType(of some: Any) -> String {
    let string = (some is Any.Type) ? String(reflecting: some) : String(reflecting: type(of: some))
    return string
}

用法:

print(stringType(of: SomeClass()))     // "SomeClass"
print(stringType(of: SomeClass.self))  // "SomeClass"
print(stringType(of: String()))        // "String"
print(fullStringType(of: String()))    // "Swift.String"

2016年9月更新

Swift 3.0:使用type(of:),例如type(of: someThing)(因为dynamicType关键字已被删除)

2015年10月更新:

我更新了下面的例子到新的Swift 2.0语法(例如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():

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)的博客有助于解读这些字符串:

例如:_TtSi代表Swift的内部Int类型。

Mike Ash有一篇很棒的博客文章涉及了同样的主题。