ios – 在Argo中解码泛型类型

ios – 在Argo中解码泛型类型,第1张

概述我正在使用Thoughtbot的Argo框架将 JSON对象解析为模型. 我遇到了一个问题,我有一个协议及其扩展,如此 protocol SomeProtocol { associatedtype Model func foo() }extension SomeProtocol where Model: Decodable { func foo() -> Mo 我正在使用Thoughtbot的Argo框架将 JSON对象解析为模型.

我遇到了一个问题,我有一个协议及其扩展,如此

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    }}

并且符合此协议的类看起来像这样

class SomeClass: SomeProtocol {    typealias Model = ArgoModel    func bar() {        print(foo())    }}

和这样的模型

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

(我也在使用他们的Curry库来讨论init方法)

我遇到的问题是,在SomeProtocol扩展中,关联类型Model不能被Argo解码.我得到的错误是

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

这是Swift类型系统的限制吗?还是有什么我想念的?

解决方法 在研究了一些之后,似乎这是Swift类型系统的限制,如Swift 2.3.问题的确切原因是诸如集合和monad之类的上下文类型不能符合Argo中的Decodable.所以我的模型只要不包含在集合中就可以工作.使用Swift 3.0,目标是允许

the ability to make a constrained extension conform to a new protocol (i.e.,an array of Equatable elements is 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可以是一个对象,也可以是通用方式的集合.

总结

以上是内存溢出为你收集整理的ios – 在Argo中解码泛型类型全部内容,希望文章能够帮你解决ios – 在Argo中解码泛型类型所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/web/1029673.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-23
下一篇 2022-05-23

发表评论

登录后才能评论

评论列表(0条)

保存