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

后端 未结 6 1232
别那么骄傲
别那么骄傲 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:58

    Another possible solution that might help somebody:

    Playground

    import Foundation
    
    class ClassType {
    
        static func name () -> String
        {
            return "\(T.self)".componentsSeparatedByString(".").last!
        }
    }
    
    class MyClass {
    
    }
    
    func testClassName(){
    
        let className = ClassType.name()
        print(className)
    }
    
    testClassName()
    

提交回复
热议问题