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

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

    String(describing: T.self) in Swift 3+

    var genericTypeName: String {
        return String(describing: T.self)
    }
    

    Within the generic type, get the name of type T by converting T.self or type(of: T.self) to a String. I found that type(of:) was not necessary but it's worth being aware of since in other cases it removes other details about the Type.

    The following example demonstrates getting the name of the generic type T within a struct and a class. It includes code to get the name of the containing type.

    Example including class and struct

    struct GenericStruct {
        var value: T
    
        var genericTypeName: String {
            return String(describing: T.self)
        }
    
        var genericTypeDescription: String {
            return "Generic Type T: '\(genericTypeName)'"
        }
    
        var typeDescription: String {
            // type(of:) is necessary here to exclude the struct's properties from the string
            return "Type: '\(type(of: self))'"
        }
    }
    
    class GenericClass {
        var value: T
    
        var genericTypeName: String {
            return String(describing: T.self)
        }
    
        var genericTypeDescription: String {
            return "Generic Type T: '\(genericTypeName)'"
        }
    
        var typeDescription: String {
            let typeName = String(describing: self)
            return "Type: '\(typeName)'"
        }
    
        init(value: T) {
            self.value = value
        }
    }
    
    enum TestEnum {
        case value1
        case value2
        case value3
    }
    
    let intGenericStruct: GenericStruct = GenericStruct(value: 1)
    print(intGenericStruct.typeDescription)
    print(intGenericStruct.genericTypeDescription)
    
    let enumGenericStruct: GenericStruct = GenericStruct(value: .value2)
    print(enumGenericStruct.typeDescription)
    print(enumGenericStruct.genericTypeDescription)
    
    let intGenericClass: GenericClass = GenericClass(value: 1)
    print(intGenericClass.typeDescription)
    print(intGenericClass.genericTypeDescription)
    
    let enumGenericClass: GenericClass = GenericClass(value: .value2)
    print(enumGenericClass.typeDescription)
    print(enumGenericClass.genericTypeDescription)
    

    Console Output

    /*
    Type: 'GenericStruct'
    Generic Type T: 'Int'
    
    Type: 'GenericStruct'
    Generic Type T: 'TestEnum'
    
    Type: 'GenericClass'
    Generic Type T: 'Int'
    
    Type: 'GenericClass'
    Generic Type T: 'TestEnum'
    */
    

提交回复
热议问题