ios - Mantle - Transform String to Enum Value -
in user
class, have defined type
property , usertype
enum. type
property received string
value in json:
{ "type" : "admin" }
i use mantle
transform string
value usertype
enum object , string
during serialization , de-serialization, respectively. have searched through other posts , mantle documentation not working properly. here's attempt:
enum usertype:string { case normal case admin } class user: mtlmodel, mtljsonserializing { var type:usertype? static func jsonkeypathsbypropertykey() -> [nsobject : anyobject]! { return ["type" : "type"] } static func jsontransformerforkey(key: string!) -> nsvaluetransformer! { if (key == "type") { return nsvaluetransformer(forname: "usertypevaluetransformer") } return nil } } // custom transformer class usertypevaluetransformer : nsvaluetransformer { override func transformedvalue(value: anyobject?) -> usertype { let thevalue:string? = (value as? string) return ((thevalue! == "admin") ? usertype.admin : usertype.normal) } override func reversetransformedvalue(value: anyobject?) -> anyobject? { let thevalue:usertype = (value as! usertype) return ((thevalue == usertype.admin) ? "admin" : "normal") } }
in code above, made custom transformer converting string
usertype
enum value , back. have overridden mantle's
jsontransformerforkey
method , specified custom transformer type
property in order perform conversion. when try serialize json user
object, receive error message:
type not property of user
type
property of user
model, going on making mantle
not able recognize it.
what should change in implementation string
enum conversion work? in advance help!
i go around problem way, using swift enumeration's raw values:
enum usertype: string { case normal = "normal" case admin = "admin" } let string = "admin" let value = usertype(rawvalue:string) //returns .admin let value = usertype.normal let string = value.rawvalue() //returns "normal"
Comments
Post a Comment