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


当前回答

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

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

其他回答

我为自己开发的类(或您可以访问的类)找到了一个解决方案。

在你的对象类定义中放置以下计算属性:

var className: String? {
    return __FILE__.lastPathComponent.stringByDeletingPathExtension
}

现在你可以像这样简单地调用对象的类名:

myObject.className

请注意,只有当类定义是在与您想要的类名称完全相同的文件中创建时,这才会起作用。

因为这是常见的情况,上面的答案应该做的大多数情况下。但在某些特殊情况下,你可能需要想出一个不同的解决方案。


如果你需要类(文件)本身的类名,你可以简单地使用这一行:

let className = __FILE__.lastPathComponent.stringByDeletingPathExtension

也许这个方法能帮助到一些人。

从Xcode 6.3到Swift 1.2,你可以简单地将类型值转换为完整的需求型字符串。

toString(Int)                   // "Swift.Int"
toString(Int.Type)              // "Swift.Int.Type"
toString((10).dynamicType)      // "Swift.Int"
println(Bool.self)              // "Swift.Bool"
println([UTF8].self)            // "Swift.Array<Swift.UTF8>"
println((Int, String).self)     // "(Swift.Int, Swift.String)"
println((String?()).dynamicType)// "Swift.Optional<Swift.String>"
println(NSDate)                 // "NSDate"
println(NSDate.Type)            // "NSDate.Type"
println(WKWebView)              // "WKWebView"
toString(MyClass)               // "[Module Name].MyClass"
toString(MyClass().dynamicType) // "[Module Name].MyClass"

Xcode 8 Swift 3.0使用类型:

let className = "\(type(of: instance))"

请看看下面的代码片段,让我知道你是否在寻找下面这样的东西。

var now = NSDate()
var soon = now.addingTimeInterval(5.0)

var nowDataType = Mirror(reflecting: now)
print("Now is of type: \(nowDataType.subjectType)")

var soonDataType = Mirror(reflecting: soon)
print("Soon is of type: \(soonDataType.subjectType)")

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

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