'Print Struct name in swift
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.
Solution 1:[1]
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.
Solution 2:[2]
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.
Solution 3:[3]
print("\(String(describing: Self.self))")
Solution 4:[4]
Convenience protocol with extension:
import Foundation
public protocol Describable {
var typeName: String { get }
}
extension Describable {
public var typeName: String {
return String(describing: Self.self)
}
}
Usage example:
struct AccountLoginRequest: Equatable, Codable, Describable
{
let email: String?
let password: String?
var description: String {
return "[\(typeName) email=\(email), password=\(password)]"
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Kilian |
Solution 2 | Community |
Solution 3 | hstdt |
Solution 4 | BadmintonCat |