首页 > 解决方案 > Swift获取通用数组的元素类型

问题描述

  1. 如何确定 Swift Generic 是一个数组?
  2. 如何实例化特定元素的数组?

我想我结束了解决方案。谢谢你的帮助。

在类似的情况下:

var value: Any?
func get() -> T? {

    switch T.self {

    case is Int:
        return Int(self.value) as? T

    case let MT as MyProtocol.Type:

        return MT.init(self.value) as? T // Perfectly

    case let MTA as Array<MyProtocol>.Type: // <== Never case, why?

        let values = self.valueAsEEArray()
        return values?.map { TMA.Element.init($0) } as? T
//                                       ^ Protocol type 'Array<MyProtocol>.Element' (aka 'MyProtocol') cannot be instantiated
protocol MyProtocol {
    init(_ value: EE)
}

标签: swiftgenericstypescasting

解决方案


您只需要再写一个返回类型为 T 的数组的函数:

func get() -> [T] {
  //Code
}

推荐阅读