Alamofire ObjectMapper, Int to enum 是不正确的



我正在使用Alamofire和ObjectMapper。我需要将 Int 转换为枚举。代码如下:

enum CountryCode: Int {
    /**
     Hong Kong
     Raw value: 852
     */
    case HK = 852
    /**
     Singapore
     Raw value: 65
     */
    case SG = 65
    /**
     Taiwan
     Raw value: 886
     */
    case TW = 886
    /**
     China
     Raw value: 86
     */
    case CN = 86
}
func mapping(map: Map) {
        countryCode <- (
            map["country_code"],
            TransformOf<CountryCode, Int>(fromJSON: { (value: Int?) -> CountryCode in
                return CountryCode(rawValue: value ?? CountryCode.HK.rawValue)!
                }, toJSON: { (value: CountryCode?) -> Int? in
                    return value?.rawValue
            })
        )
}

返回的值每次都默认为 HK,无论 Int 值是什么。知道我在这里做错了什么吗?

为什么必须创建自定义TransformOf实例?由于您的国家/地区代码具有默认值,因此您可以在字段声明中按如下方式分配它:

var countryCode : CountryCode =  CountryCode.HK

然后在映射函数中使用默认的 ObjectMapper 的 EnumTransform

countryCode <- (map["country_code"],EnumTransform<CountryCode>())

最新更新