Print Struct name in swift

冷暖自知 提交于 2020-03-21 11:00:07

问题


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.


回答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.




回答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.




回答3:


print("\(String(describing: Self.self))")


来源:https://stackoverflow.com/questions/35088970/print-struct-name-in-swift

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!