gpt4 book ai didi

ios - Object Mapper - 解析 [AnyObject] 的数组

转载 作者:可可西里 更新时间:2023-11-01 01:32:47 27 4
gpt4 key购买 nike

我有来自 API 的多类型对象的响应 JSON。

它里面有 type 属性。现在我正在尝试应用某种基于 type 属性的自动映射,但我无法以任何方式使其工作。

private let modelClassMap = [
"first_type": First.self
]

func createModelWithDictionary(json: [String: AnyObject]) -> [AnyObject] {
var items: [AnyObject]
if let items = json["items"] as? [[String: AnyObject]] {
for item in items {
if let typeString = item["type"] as? String {
var Type = self.modelClassMap[typeString]
items.append(Mapper<Type>().map(item))
}
}
}
return items
}

我得到的错误是 Type is not a type

最佳答案

您尝试做的事情实际上是不可能的,因为模板的关联类型不是运行时的。编译器需要在编译时知道类型。

我们可以使用枚举来做一些不同的事情:

enum ModelClassMap: String {
case FirstType = "first_type"

func map(item: [String: AnyObject]) -> AnyObject? {
switch self {
case FirstType:
return Mapper<First>().map(item)
}
}
}

在您的 for 循环中,您可以尝试将字符串转换为枚举:

func createModelWithDictionary(json: [String: AnyObject]) -> [AnyObject] {
var mappedItems: [AnyObject] = []
if let items = json["items"] as? [[String: AnyObject]] {
items.forEach() {
if let typeString = $0["type"] as? String,
let mappedType = ModelClassMap(rawValue: typeString),
let mappedObject = mappedType.map($0) {
// mappedObject represents an instance of required object, represented by "type"
mappedItems.append(mappedObject)
}
}
}
return mappedItems
}

关于ios - Object Mapper - 解析 [AnyObject] 的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38992692/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com