swift - Swift获取通用数组的元素类型
问题描述
- 如何确定 Swift Generic 是一个数组?
- 如何实例化特定元素的数组?
我想我结束了解决方案。谢谢你的帮助。
在类似的情况下:
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)
}
解决方案
您只需要再写一个返回类型为 T 的数组的函数:
func get() -> [T] {
//Code
}
推荐阅读
- javascript - 子组件 Vue.JS 上未显示道具数据
- c# - Autofac:基于条件/参数解析以删除用于实例化的 Switch 语句
- vb.net - 导航栏类型选择器不会自动跳转到编码方法
- php - 使用 PHP PDO 从 CSV 从 mysql 插入数据
- ssl - NiFi:配置 SSLContext、Truststore 或 Keystore 认证
- cxf - 如何避免 CXF codegen 更改架构中的元素名称?
- php - 使用带有 CURL 的代理时出错
- c# - 无法在设计器中修改数据集 - 似乎无法找到连接字符串
- reactjs - 如何在 ReactJs 中渲染包含对象的数组?
- c - 如何包含
?