Print Struct name in swift

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

Tags:

Struct

Swift