2016-07-13 4 views
2

die folgende vereinfachte Struktur verwendet:Wie benutzerdefinierte Enum/RawRepresentable zu Wörterbuch mit ObjectMapper zuordnen?

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>()) 
    } 
} 

... mit diesem JSON:

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

... erzeugt, wenn EnumTransform() verwendet, wie die folgenden (angemessenen) Trans Fehler kompilieren:

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

Wie also muss ein benutzerdefinierter TransformType aussehen, um das Wörterbuch richtig zuzuordnen?

Sie können die Quelle von EnumTransform finden Sie hier: https://github.com/Hearst-DD/ObjectMapper/blob/master/ObjectMapper/Transforms/EnumTransform.swift

Dank!

Antwort

1

TransformTypes sind IMHO primär entwickelt, um Werte und nicht Schlüssel zu transformieren. Und Ihr Beispiel ist ein bisschen kompliziert, denn auch der Wert ist nicht nur ein Grundtyp.

Was denkst du über diesen kleinen Hack?

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 
       } 
      } 
     } 
    } 
} 
Verwandte Themen