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

标签 ios swift enums nsdictionary objectmapper

使用以下简化结构:

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/

相关文章:

ios - Objective-C 内存使用情况

Android Native to Flutter 无法在主 channel 中工作

ios - iPad OS 13 beta UIWebView在开关输入上崩溃

ios - 尝试通过快速桥接头调用扩展方法时发送到实例的无法识别的选择器

enums - f# 强制转换枚举元素类型

ios - NSBundle bundleWithIdentifier 为静态框架和资源包返回 null

ios - 在 Swift 中,如何防止函数在子类上被调用?

ios - 如何增加特定部分中特定单元格的高度

java - 是否可以弃用枚举常量?

typescript 标记的枚举获取值