JSON icon indicating copy to clipboard operation
JSON copied to clipboard

Provide a default decode for RawRepresentable type

Open nanoxd opened this issue 8 years ago • 0 comments

👋 I was wondering if there was interest in me adding a default decode function for RawRepresentable types?

An example of what I'm using in my own project:

func decode<T: RawRepresentable>(_ dictionary: JSONDictionary, key: String) throws -> T {
    let object: Any = try decode(dictionary, key: key)
    
    guard let rawValue = object as? T.RawValue else {
        throw JSONDeserializationError.invalidAttributeType(key: key, expectedType: T.self, receivedValue: object)
    }
    
    guard let value = T(rawValue: rawValue) else {
       // Ideally represented by a new error case called `.invalidRawValue(key: key, rawValue: rawValue)`
        throw JSONDeserializationError.invalidAttribute(key: key)
    }
    
    return value
}

If there's interest, I can add the code, add a specific error case, update the readme, and add tests 😄 .

Regardless, thanks for the project. It's been a pleasure to work with.

nanoxd avatar May 28 '17 04:05 nanoxd