【问题标题】:Swift Get Generic Type of ArraySwift 获取数组的通用类型
【发布时间】:2017-02-06 17:22:45
【问题描述】:

我需要得到一个数组的泛型。

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

【问题讨论】:

标签: arrays swift generics types dynamictype


【解决方案1】:

您可以使用计算属性扩展 Array,该属性公开其泛型类型参数 Element

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

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

【讨论】:

  • 我会试一试。看起来它可以满足我的需求。
  • 它确实有效,但我仍在寻找更好的方法
  • 也遇到了选角问题,我不得不这样做。如果您有想法,我将不胜感激。发布了一个新问题,因为从技术上讲这个回答这个问题就好了。 stackoverflow.com/questions/39753881/…
猜你喜欢
  • 1970-01-01
  • 2015-05-06
  • 1970-01-01
  • 1970-01-01
  • 2012-02-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多