Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Print Struct name in swift

Tags:

struct

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.

like image 815
Nosakhare Belvi Avatar asked Jan 29 '16 16:01

Nosakhare Belvi


3 Answers

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.

like image 114
Eric Aya Avatar answered Nov 20 '22 04:11

Eric Aya


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.

like image 24
hnh Avatar answered Nov 20 '22 05:11

hnh


print("\(String(describing: Self.self))")
like image 29
hstdt Avatar answered Nov 20 '22 06:11

hstdt