Swift 获取通用类型的数组

Swift Get Generic Type of Array

我需要获取数组的泛型类型。

我有一个 Array<Decodable> 的对象,但我不能保证泛型类型总是 Decodable。我知道我可以通过说 array.self.dynamicType 来获取 Array.Type,但我需要像 array.generic.self.dynamicType 这样的东西来获取 Decodable.Type。我该怎么做?

您可以使用公开其通用类型参数的计算 属性 扩展 Array Element:

extension Array {
    var ElementType: Element.Type {
        return Element.self
    }
}

print([1, 2, 3].dynamicType) //Array<Int>
print([1, 2, 3].ElementType) //Int