是否有一种方法可以在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 3.0中,你可以使用type(of:),因为dynamicType关键字已被删除。

其他回答

当使用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

上面的答案没有使用type(of:的新方法的工作示例。所以为了帮助像我这样的新手,这里有一个工作的例子,主要来自苹果的文档- https://developer.apple.com/documentation/swift/2885064-type

doubleNum = 30.1

func printInfo(_ value: Any) {
    let varType = type(of: value)
    print("'\(value)' of type '\(varType)'")
}

printInfo(doubleNum)
//'30.1' of type 'Double'

编辑:在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版本4:

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

谢谢@Joshua Dance