Generic decoding in Argo

I am using the Thoughtbot Argo structure to parse JSON objects in the model.

I ran into a problem when I have a protocol and its extension as such

protocol SomeProtocol {
    associatedtype Model
    func foo()     
}

extension SomeProtocol where Model: Decodable {
    func foo() -> Model? {
        // someJSON is AnyObject in this case, say, from a network call
        guard let model: Model = decode(someJSON) else { return nil }
        return model
    }
}

and the class corresponding to this protocol looks something like this:

class SomeClass: SomeProtocol {
    typealias Model = ArgoModel

    func bar() {
        print(foo())
    }
}

and a model like this

struct ArgoModel {
    let id: String
}

extension ArgoModel: Decodable {
    static func decode(j: AnyObject) -> Decoded<ArgoModel> {
        return curry(self.init)
            <^> j <| "id"
    }
}

(I also use their Curry library to curry the init method)

The problem I encountered is that in the SomeProtocol extension, the associated Model type cannot be decrypted by Argo. The error I get is this

No 'decode' candidates produced the expected contextual result type 'Self.Model?'

Is this a limitation of a system like Swift? Or am I missing something?

+4
source share
1 answer

, Swift Swift 2.3. , , , Decodable Argo. , . Swift 3.0 ,

(.. Equatable Equatable)

: https://github.com/thoughtbot/Argo/issues/334

, SomeProtocol. , :

struct ArgoModels {
    let models: [ArgoModel]
}

extension ArgoModels: Decodable {
    static func decode(j: JSON) -> Decoded<ArgoModels> {
        switch j {
            case .Array(let a):
                return curry(self.init) <^> sequence(a.map(ArgoModel.decode))
            default:
                return .typeMismatch("Array", actual: j)
        }
    }
}

struct ArgoModel {
    let id: String
}

extension ArgoModel: Decodable {
    static func decode(j: AnyObject) -> Decoded<ArgoModel> {
        return curry(self.init)
            <^> j <| "id"
    }
}

typealias, Model, , .

+1

All Articles