iosswiftenumsgithub-mantlensvaluetransformer

Mantle - Transform String to Enum Value


In my User class, I have defined a type property and a UserType enum. The type property is received as a String value in the JSON:

{
    "type" : "Admin"
}

I would like to use Mantle to transform the String value into a UserType enum object and back to a String during serialization and de-serialization, respectively. I have searched through other SO posts and the Mantle documentation but could not get this working properly. Here's my 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 the code above, I made a custom transformer for converting a String to a UserType enum value and back. I have overridden Mantle's JSONTransformerForKey method and specified my custom transformer for the type property in order to perform the conversion. When I try to serialize the JSON into a User object, I receive this error message:

type is not a property of User

type is clearly a property of the User model, but something is going on that is making Mantle not able to recognize it.

What should I change in my implementation to get the String to enum conversion to work? Thanks in advance for any help!


Solution

  • I would go around your problem another way, by 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"