gpt4 book ai didi

ios - 如何使用 ObjectMapper 将自定义 Enum/RawRepresentable 映射到字典?

转载 作者:可可西里 更新时间:2023-11-01 02:16:13 30 4
gpt4 key购买 nike

使用以下简化结构:

class Property: Mappable {
var path: String?

override func mapping(map: Map) {
path <- map["path"]
}
}

class Specification {
enum Name: String {
case Small = "SMALL"
case Medium = "MEDIUM"
}
}

class ItemWithImages: Mappable {
var properties: [Specification.Name : Property]?

override func mapping(map: Map) {
properties <- (map["properties"], EnumTransform<Specification.Name>())
}
}

... 使用该 JSON:

[{"properties: ["SMALL": {"path": "http://..."}, "MEDIUM": {"path": "http://..."}]}]

... 使用 EnumTransform() 作为 Transform 时会产生以下(合理的)编译错误:

Binary operator '<-' cannot be applied to operands of type '[Specification.Name : Property]?' and '(Map, EnumTransform<Specification.Name>)'

那么自定义 TransformType 必须是什么样子才能以正确的方式映射该字典?

您可以在这里找到 EnumTransform 的源代码:https://github.com/Hearst-DD/ObjectMapper/blob/master/ObjectMapper/Transforms/EnumTransform.swift

谢谢!

最佳答案

TransformTypes 恕我直言,主要设计用于转换值而不是键。而且您的示例有点复杂,因为即使值也不仅仅是基本类型。

你觉得这个小技巧怎么样?

struct ItemWithImages: Mappable {
var properties: [Specification.Name : Property]?

init?(_ map: Map) {
}

mutating func mapping(map: Map) {
let stringProperties: [String: Property]?
// map local variable
stringProperties <- map["properties"]

// post process local variable
if let stringProperties = stringProperties {
properties = [:]
for (key, value) in stringProperties {
if let name = Specification.Name(rawValue: key) {
properties?[name] = value
}
}
}
}
}

关于ios - 如何使用 ObjectMapper 将自定义 Enum/RawRepresentable 映射到字典?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38346482/

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