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

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

    It's possible if your type parameter implements a common naming protocol.

    In the example below the protocol Named ensures that the generic type implements the name class property.

    Note that this works with both classes and value types since the latter can also be extended to conform to protocols, as illustrated with the Int below.

    protocol Named {
        class var name: String { get }
    }
    
    class MyClass {
        func genericName() -> String {
            return T.name
        }
    }
    
    extension Int: Named {
        static var name: String { return "I am an Int" }
    }
    
    class Foo: Named {
        class var name: String { return "I am a Foo" }
    }
    
    enum Drink: Named {
        static var name: String { return "I am a Drink" }
    }
    
    MyClass().genericName()  // I am an Int
    MyClass().genericName()  // I am a Foo
    MyClass().genericName()  // I am a Drink
    

提交回复
热议问题