获取泛型类型T的名称为String

时间:2017-02-10 19:07:16

标签: swift generics

给定如下所示的泛型类型,如何将类型名称“T”作为字符串。我计划将其用于日志记录,或者可能在字典的String密钥中使用。

struct GenericStruct<T> {
    var value: T
}

1 个答案:

答案 0 :(得分:3)

Swift 3中的

T.self

在通用类型中,通过将TT.self转换为type(of: T.self)来获取类型String的名称。我发现type(of:)没有必要,但值得注意,因为在其他情况下,它会删除有关Type的其他详细信息。

以下示例演示了如何在结构和类中获取泛型类型T的名称。我还包含了获取包含类型名称的代码。

实施例

struct GenericStruct<T> {
    var value: T

    var genericTypeDescription: String {
        return "Generic Type T: '\(T.self)'"
    }

    var typeDescription: String {
        // type(of:) is necessary to exclude the struct's properties from the string
        return "Type: '\(type(of: self))'"
    }
}

class GenericClass<T> {
    var value: T

    var genericTypeDescription: String {
        let typeName = String(describing: T.self) // use this to get the type name alone
        return "Generic Type T: '\(typeName)'"
    }

    var typeDescription: String {
        let typeName = String(describing: self) // use this to get the type name alone
        return "Type: '\(typeName)'"
    }

    init(value: T) {
        self.value = value
    }
}

enum TestEnum {
    case value1
    case value2
    case value3
}

let intGenericStruct: GenericStruct<Int> = GenericStruct(value: 1)
print(intGenericStruct.typeDescription)
print(intGenericStruct.genericTypeDescription)

let enumGenericStruct: GenericStruct<TestEnum> = GenericStruct(value: .value2)
print(enumGenericStruct.typeDescription)
print(enumGenericStruct.genericTypeDescription)

let intGenericClass: GenericClass<Int> = GenericClass(value: 1)
print(intGenericClass.typeDescription)
print(intGenericClass.genericTypeDescription)

let enumGenericClass: GenericClass<TestEnum> = GenericClass(value: .value2)
print(enumGenericClass.typeDescription)
print(enumGenericClass.genericTypeDescription)

控制台输出

Type: 'GenericStruct<Int>'
Generic Type T: 'Int'

Type: 'GenericStruct<TestEnum>'
Generic Type T: 'TestEnum'

Type: 'GenericClass<Swift.Int>'
Generic Type T: 'Int'

Type: 'GenericClass<TestEnum>'
Generic Type T: 'TestEnum'
相关问题