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


当前回答

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

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

其他回答

let i: Int = 20


  func getTypeName(v: Any) -> String {
    let fullName = _stdlib_demangleName(_stdlib_getTypeName(i))
    if let range = fullName.rangeOfString(".") {
        return fullName.substringFromIndex(range.endIndex)
    }
    return fullName
}

println("Var type is \(getTypeName(i)) = \(i)")

我在这里尝试了一些其他的答案,但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。

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

编辑:在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。

斯威夫特3.0

let string = "Hello"
let stringArray = ["one", "two"]
let dictionary = ["key": 2]

print(type(of: string)) // "String"

// Get type name as a string
String(describing: type(of: string)) // "String"
String(describing: type(of: stringArray)) // "Array<String>"
String(describing: type(of: dictionary)) // "Dictionary<String, Int>"

// Get full type as a string
String(reflecting: type(of: string)) // "Swift.String"
String(reflecting: type(of: stringArray)) // "Swift.Array<Swift.String>"
String(reflecting: type(of: dictionary)) // "Swift.Dictionary<Swift.String, Swift.Int>"