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


当前回答

这里的许多答案都不支持最新的Swift(本文撰写时为Xcode 7.1.1)。

目前获取信息的方法是创建一个Mirror并对其进行询问。对于类名,它很简单:

let mirror = Mirror(reflecting: instanceToInspect)
let classname:String = mirror.description

关于对象的其他信息也可以从镜像中检索。详情见http://swiftdoc.org/v2.1/type/Mirror/。

其他回答

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

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)")

当使用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实现。

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

这就是如何获得对象或type的类型字符串,它是一致的,并考虑到对象定义属于哪个模块或嵌套在哪个模块中。适用于Swift 4.x。

@inline(__always) func typeString(for _type: Any.Type) -> String {
    return String(reflecting: type(of: _type))
}

@inline(__always) func typeString(for object: Any) -> String {
    return String(reflecting: type(of: type(of: object)))
}

struct Lol {
    struct Kek {}
}

// if you run this in playground the results will be something like
typeString(for: Lol.self)    //    __lldb_expr_74.Lol.Type
typeString(for: Lol())       //    __lldb_expr_74.Lol.Type
typeString(for: Lol.Kek.self)//    __lldb_expr_74.Lol.Kek.Type
typeString(for: Lol.Kek())   //    __lldb_expr_74.Lol.Kek.Type

我在这里尝试了一些其他的答案,但milage似乎很清楚下面的对象是什么。

然而,我确实发现了一种方法,你可以通过以下方式获得对象的object - c类名:

now?.superclass as AnyObject! //replace now with the object you are trying to get the class name for

下面是一个如何使用它的例子:

let now = NSDate()
println("what is this = \(now?.superclass as AnyObject!)")

在本例中,它将在控制台中打印NSDate。

要在Swift中获得对象类型或对象类,您必须使用类型(of: youobject)

类型(:yourObject)