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


当前回答

这在检查一个对象是否是类的类型时也很方便:

if someObject is SomeClass {
    //someObject is a type of SomeClass
}

其他回答

您仍然可以通过className(返回String)访问该类。

实际上有几种方法来获取类,例如classForArchiver, classForCoder, classForKeyedArchiver(都返回AnyClass!)

无法获取原语的类型(原语不是类)。

例子:

var ivar = [:]
ivar.className // __NSDictionaryI

var i = 1
i.className // error: 'Int' does not have a member named 'className'

如果你想获取一个原语的类型,你必须使用bridgetooobjecvec()。例子:

var i = 1
i.bridgeToObjectiveC().className // __NSCFNumber

编辑:在Swift 1.2 (Xcode 6.3)中引入了一个新的toString函数。

你现在可以使用.self和使用.dynamicType打印任意类型的需求类型:

struct Box<T> {}

toString("foo".dynamicType)            // Swift.String
toString([1, 23, 456].dynamicType)     // Swift.Array<Swift.Int>
toString((7 as NSNumber).dynamicType)  // __NSCFNumber

toString((Bool?).self)                 // Swift.Optional<Swift.Bool>
toString(Box<SinkOf<Character>>.self)  // __lldb_expr_1.Box<Swift.SinkOf<Swift.Character>>
toString(NSStream.self)                // NSStream

试着调用你的类。self和youobject . dynamictype。

参考:https://devforums.apple.com/thread/227425。

Swift 3.0, Xcode 8

使用下面的代码,您可以向实例请求其类。你也可以比较两个实例,是否具有相同的类。

// CREATE pure SWIFT class
class MySwiftClass {
    var someString : String = "default"
    var someInt    : Int = 5
}

// CREATE instances
let firstInstance = MySwiftClass()
let secondInstance = MySwiftClass()
secondInstance.someString = "Donald"
secondInstance.someInt = 24

// INSPECT instances
if type(of: firstInstance) === MySwiftClass.self {
    print("SUCCESS with ===")
} else {
    print("PROBLEM with ===")
}

if type(of: firstInstance) == MySwiftClass.self {
    print("SUCCESS with ==")
} else {
    print("PROBLEM with ==")
}

// COMPARE CLASS OF TWO INSTANCES
if type(of: firstInstance) === type(of: secondInstance) {
    print("instances have equal class")
} else {
    print("instances have NOT equal class")
}

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

类型(:yourObject)

Swift版本4:

print("\(type(of: self)) ,\(#function)")
// within a function of a class

谢谢@Joshua Dance