evermeer / AlamofireJsonToObjects

An Alamofire extension which converts JSON response data into swift objects using EVReflection
Other
161 stars 28 forks source link

Issue with int key named count #5

Closed sagits closed 9 years ago

sagits commented 9 years ago

Hi, im having an issue with an property named count:

---> setValue 'MetaModel {
   hash = 1667855328
   key = status, value = SUCCESS
   key = count, value = 0
}
' for key '_meta' should be handled.
class MetaModel : EVObject {
    var status: String?
    var count: Int?

    override func setValue(value: AnyObject!, forUndefinedKey key: String) {
        switch key {
        case "count":
             count = 0 // just to test, without this code is always <null>
        default:
            NSLog("---> setValue for key '\(key)' should be handled.")
        }
    }

}

If i wont handle 'count' case it always shows:

---> setValue 'MetaModel {
   hash = 1676107560
   key = status, value = SUCCESS
   key = count, value = <null>
}

Is there any issue with the key 'code' ? (is it a keyword maybe) ? Thanks in advance.

evermeer commented 9 years ago

The object mapping in AlamofireJsonToObjects is don by the library EVReflection. EVReflection has 2 unit test classes with workarounds for handling issues that are not supported by Swift.

count is not a keyword. You are allowed to create a property named count. If you do have data that has a keyword as a key, then just add an underscore in front of it. for instance: var _public: String

In this case the issue is that the only way a value can be set without directly assigning it is by executing the setValue forKey function on the object. That is the basis of EVReflection. For some reason Swift does not support that for the following types:

  1. Nullable type fields like Int? Float?, etc.
  2. Enum values
  3. Arrays with nullable objects. The base workaround for these is handling it in the setValue forUndefinedKey function like you did. For the nullable Int there is an other alternative. You could use a nullable NSNumber instead. Or maybe you could change it to just an int and assign 0 to it as a default value.