It is possible to know the name of a struct in swift ? I know this is possible for class
:
Example
class Example {
var variable1 = "one"
var variable2 = "2"
}
printing this class name, I would simply do:
NSStringFromClass(Example).componentsSeparatedByString(".").last!
but can I do something similar for struct
?
Example
If i have a struct
:
struct structExample {
var variable1 = "one"
var variable2 = "2"
}
how can I get the name "structExample" of this struct
?
Thanks.
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"
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"
Regarding Swift 3, self.dynamicType
has been renamed to type(of: self)
for the example here.
The pure Swift version of this works for structs just like for classes: https://stackoverflow.com/a/31050781/2203005.
If you want to work on the type object itself:
let structName = "\(structExample.self)"
If you have an instance of the struct:
var myInstance = structExample()
let structName = "\(myInstance.dynamicType)"
Funny enough the Type object returned does not seem to conform to the CustomStringConvertible protocol. Hence it has no 'description' property, though the "" pattern still does the right thing.
print("\(String(describing: Self.self))")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With