Get the name (string) of a generic type in Swift

后端 未结 6 1230
别那么骄傲
别那么骄傲 2020-12-17 08:10

I have a generic class of type T and I would like to get the name of the type that passed into the class when instantiated. Here is an example.

class MyClas         


        
6条回答
  •  自闭症患者
    2020-12-17 08:44

    You can return any types' name by using string interpolation:

    class MyClass {
        func genericName() -> String {
            return "\(T.self)"
        }
    }
    

    You can try it in a playground and it works as expected:

    var someClass = MyClass()
    someClass.genericName() // Returns "Swift.String"
    

提交回复
热议问题