我有来自 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
}
我收到的错误是类型不是类型
最佳答案
您想要做的事情实际上是不可能的,因为模板的关联类型不是运行时的。编译器需要在编译时知道类型。
我们可以使用枚举做一些不同的事情:
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 - 对象映射器 - 解析 [AnyObject] 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38992692/