我需要获取数组的通用类型。Swift获取数组的通用类型
我有一个对象是Array<Decodable>
,但我不能保证泛型类型总是Decodable
。我知道我可以通过说array.self.dynamicType
来得到Array.Type
,但我需要类似array.generic.self.dynamicType
来得到Decodable.Type
。我将如何做到这一点?
我需要获取数组的通用类型。Swift获取数组的通用类型
我有一个对象是Array<Decodable>
,但我不能保证泛型类型总是Decodable
。我知道我可以通过说array.self.dynamicType
来得到Array.Type
,但我需要类似array.generic.self.dynamicType
来得到Decodable.Type
。我将如何做到这一点?
您可以用公开其泛型类型参数Element
一个计算性能扩展Array
:
extension Array {
var ElementType: Element.Type {
return Element.self
}
}
print([1, 2, 3].dynamicType) //Array<Int>
print([1, 2, 3].ElementType) //Int
我会给这个镜头。看起来它可以做我需要的。 – steventnorris
它当然有效,但我仍然在寻找更好的方法 – Alexander
也遇到了铸造问题,我必须这样做。如果你有想法,我会很感激他们。发表了一个新问题,因为技术上这个答案这个问题就好了。 http://stackoverflow.com/questions/39753881/determine-object-type-of-array-element-parameter – steventnorris
你怎么只'Array.Type'打印? ['print([1,2,3] .dynamicType)'产生'Array'](http://swiftlang.ng.bluemix.net/#/repl/57ebf024ad13d8063ad09cfc),而不仅仅是'Array'。如果您希望获得高质量的答案,则必须使用更多[具体的,最小的,完整的和可验证的示例。](http://stackoverflow.com/help/mcve) –
Alexander
@AlexanderMomchliov是的,它确实给出了阵列,但那是Array.Type。应该澄清得更好。这似乎无关紧要,因为我不关心那件作品。我只想要泛型类型。 –
steventnorris