thoughtbot/Argo

Generic parser: Question

hrachyastepanyan opened this issue · 2 comments

Hello.
I have a question. I want to create a function which parses any objects with given generic type.
Function is like:

func parse<T: Decodable>(response: Any, type: T.Type) -> ParserResult<T, NSError> {
        
        let jsonModel = JSON(response)
        let decodedModel = T.decode(jsonModel)
        
        if let error = decodedModel.error {
            
            ...
        }
        else if let unwrappedModel = decodedModel.value {
            
            ...
        }
        else {
            
            ...
        }
}

I have a model which conforms to the Decodable protocol.
When I call this function with the array of that model type as type parameter like:

parse(response: response, type: [MyModelClass].self)

I get this compile time error:

In argument type '[MyModelClass].Type' (aka 'Array<MyModelClass>.Type'), '[MyModelClass]' does not conform to expected type 'Decodable'.

How can I fix this?
Thanks!

Argo (4.1.0)

I think you're doing more work than necessary in general? The function you're trying to define seems really similar to the decode function we already provide.

That being said, the issue you're running into is that arrays of decodable types aren't themselves decodable. This is why we provide the <|| and <||? operators in Argo. If you wanted to write this function yourself you'd need to write a function that explicitly takes [T.Type].

I'm going to go ahead and close this due to inactivity but please feel free to reopen if this is still an issue.