本文翻译自:How do I print the type or class of a variable in Swift?
Is there a way to print the runtime type of a variable in swift? 有没有办法在swift中打印变量的运行时类型? For example: 例如:
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
In the example above, I'm looking for a way to show that the variable "soon" is of type ImplicitlyUnwrappedOptional<NSDate>
, or at least NSDate!
在上面的例子中,我正在寻找一种方法来表明变量“很快”是ImplicitlyUnwrappedOptional<NSDate>
,或者至少是NSDate!
. 。
#1楼
参考:https://stackoom.com/question/1cj6D/如何在Swift中打印变量的类型或类
#2楼
You can still access the class, through className
(which returns a String
). 您仍然可以通过className
(返回String
)访问该类。
There are actually several ways to get the class, for example classForArchiver
, classForCoder
, classForKeyedArchiver
(all return AnyClass!
). 实际上有几种获取类的方法,例如classForArchiver
, classForCoder
, classForKeyedArchiver
(都返回AnyClass!
)。
You can't get the type of a primitive (a primitive is not a class). 您无法获取基元的类型(基元不是类)。
Example: 例:
var ivar = [:]
ivar.className // __NSDictionaryI
var i = 1
i.className // error: 'Int' does not have a member named 'className'
If you want to get the type of a primitive, you have to use bridgeToObjectiveC()
. 如果要获取基元的类型,则必须使用bridgeToObjectiveC()
。 Example: 例:
var i = 1
i.bridgeToObjectiveC().className // __NSCFNumber
#3楼
Edit: A new toString
function has been introduced in Swift 1.2 (Xcode 6.3) . 编辑: Swift 1.2(Xcode 6.3)中引入了一个新的toString
函数。
You can now print the demangled type of any type using .self
and any instance using .dynamicType
: 您现在可以使用.self
和任何使用.dynamicType
实例打印任何类型的demangled类型:
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
Try calling YourClass.self
and yourObject.dynamicType
. 尝试调用YourClass.self
和yourObject.dynamicType
。
Reference: https://devforums.apple.com/thread/227425 . 参考: https : //devforums.apple.com/thread/227425 。
#4楼
There appears to be no generic way to print the type name of an arbitrary value's type. 似乎没有通用的方法来打印任意值类型的类型名称。 As others have noted, for class instances you can print value.className
but for primitive values it appears that at runtime, the type information is gone. 正如其他人所指出的,对于类实例,您可以打印value.className
但是对于原始值,似乎在运行时,类型信息消失了。
For instance, it looks as if there's not a way to type: 1.something()
and get out Int
for any value of something
. 例如,它看起来好像有没有输入方式: 1.something()
并得到了Int
为任何价值something
。 (You can, as another answer suggested, use i.bridgeToObjectiveC().className
to give you a hint, but __NSCFNumber
is not actually the type of i
-- just what it will be converted to when it crosses the boundary of an Objective-C function call.) (你可以,作为另一个答案建议,使用i.bridgeToObjectiveC().className
给你一个提示,但是__NSCFNumber
实际上并不是 i
的类型 - 只是当它穿过Objective-的边界时它将被转换为它的类型C函数调用。)
I would be happy to be proven wrong, but it looks like the type checking is all done at compile time, and like C++ (with RTTI disabled) much of the type information is gone at runtime. 我很高兴被证明是错误的,但看起来类型检查都是在编译时完成的,并且像C ++一样(禁用RTTI)很多类型信息在运行时都消失了。
#5楼
When using Cocoa (not CocoaTouch), you can use the className
property for objects that are subclasses of NSObject. 使用Cocoa(而不是CocoaTouch)时,可以将className
属性用于作为NSObject子类的对象。
println(now.className)
This property is not available for normal Swift objects, which aren't subclasses of NSObject (and in fact, there is no root id or object type in Swift). 这个属性不适用于普通的Swift对象,它们不是NSObject的子类(实际上,Swift中没有root id或对象类型)。
class Person {
var name: String?
}
var p = Person()
println(person.className) // <- Compiler error
In CocoaTouch, at this time there is not a way to get a string description of the type of a given variable. 在CocoaTouch中,目前还没有办法获得给定变量类型的字符串描述。 Similar functionality also does not exist for primitive types in either Cocoa or CocoaTouch. Cocoa或CocoaTouch中的原始类型也不存在类似的功能。
The Swift REPL is able to print out a summary of values including its type, so it is possible this manner of introspection will be possible via an API in the future. Swift REPL能够打印出包括其类型在内的值的摘要,因此将来可以通过API实现这种内省。
EDIT : dump(object)
seems to do the trick. 编辑 : dump(object)
似乎做的伎俩。
#6楼
Is this what you're looking for? 这是你在找什么?
println("\(object_getClassName(now))");
It prints "__NSDate" 它打印“__NSDate”
UPDATE : Please note this no longer seems to work as of Beta05 更新 :请注意,这似乎不再适用于Beta05