快速打印结构名称 [英] Print Struct name in swift
问题描述
可以在 swift 中知道结构的名称吗?我知道这对于 class
是可能的:
It is possible to know the name of a struct in swift ? I know this is possible for class
:
示例
class Example {
var variable1 = "one"
var variable2 = "2"
}
打印这个类名,我会这样做:
printing this class name, I would simply do:
NSStringFromClass(Example).componentsSeparatedByString(".").last!
但是我可以为 struct
做类似的事情吗?
but can I do something similar for struct
?
示例
如果我有一个 struct
:
struct structExample {
var variable1 = "one"
var variable2 = "2"
}
我怎样才能获得这个struct
的名称"structExample"?
how can I get the name "structExample" of this struct
?
谢谢.
推荐答案
如果你需要非实例化结构的名称,你可以询问它的self
:
If you need the name of the non instanciated struct you can ask for its self
:
struct StructExample {
var variable1 = "one"
var variable2 = "2"
}
print(StructExample.self) // prints "StructExample"
例如,我将使用 CustomStringConvertible 和 dynamicType:
For an instance I would use CustomStringConvertible and dynamicType:
struct StructExample: CustomStringConvertible {
var variable1 = "one"
var variable2 = "2"
var description: String {
return "\(self.dynamicType)"
}
}
print(StructExample()) // prints "StructExample"
关于 Swift 3,self.dynamicType
已重命名为 type(of: self)
以作为示例.
Regarding Swift 3, self.dynamicType
has been renamed to type(of: self)
for the example here.
这篇关于快速打印结构名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!