tristanhimmelman / ObjectMapper

Simple JSON Object mapping written in Swift
MIT License
9.14k stars 1.03k forks source link

[question] Combine Transforms #998

Open ghost opened 6 years ago

ghost commented 6 years ago

Hello, i'd like to know is there is something to combine two transform into one. like

enum OperationType: String {
          case simple = "S"
          case complex = "C"
}
let trimTransform = TransformOf<String, String>(fromJSON: { (value: String?) -> String? in
        return value?.trimmingWhiteSpaces()
    }, toJSON: { (value: String?) -> String? in
        return value
    })

let toEnum = EnumTransform<OperationType>()

then i want to combine them into one let trimAndTransformToEnum = trimTransform >> toEnum

and then use it as operation <- (map["operation"], trimAndTransformToEnum() ) or operation <- (map["operation"], trimTransform >> toEnum)

so. does exist something like >> to combine two transforms ?

thanks in advance F

ghost commented 6 years ago

the thing is, api response is

{ 
"operation" = "                   S                "
}

and i want to trim before transform to enum

gcharita commented 6 years ago

@TotaX you can achieve this by creating you own custom TransformType like:

open class TrimmingStringEnumTransform<T: RawRepresentable>: TransformType where T.RawValue == String {
    public typealias Object = T
    public typealias JSON = String

    private let charactersToTrimm: CharacterSet

    public init(charactersToTrimm: CharacterSet) {
        self.charactersToTrimm = charactersToTrimm
    }

    open func transformFromJSON(_ value: Any?) -> Object? {
        guard var raw = value as? String else {
            return nil
        }
        raw = raw.trimmingCharacters(in: charactersToTrimm)
        return T(rawValue: raw)
    }

    open func transformToJSON(_ value: T?) -> JSON? {
        guard let obj = value else {
            return nil
        }
        return obj.rawValue
    }
}

and use it in mapping(map:) function like:

operation <- (map["operation"], TrimmingStringEnumTransform(charactersToTrimm: .whitespaces))
ghost commented 6 years ago

yeah. i did that. but i wanted to know if there was something to combine two transform. anyway, thanks so much!