协议扩展的可编码(或可编码)不符合它 [英] Protocol extending Encodable (or Codable) does not conform to it

查看:98
本文介绍了协议扩展的可编码(或可编码)不符合它的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有2个协议,过滤器参数,它们都扩展了 Encodable

I have 2 protocols, Filters and Parameters, both of which extend Encodable

protocol Filters: Encodable {
    var page: Int { get }
}

protocol Parameters: Encodable {
    var type: String { get }
    var filters: Filters { get }
}

因此,我创建了符合这些协议的结构……

I create structs conforming to these protocols, thusly…

struct BankAccountFilters: Filters {
    var page: Int
    var isWithdrawal: Bool
}

struct BankAccountParamters: Parameters {
    let type: String = "Bank"
    var filters: Filters
}

let baf = BankAccountFilters(page: 1, isWithdrawal: true)
let bap = BankAccountParamters(filters: baf)

由于以下原因而失败:

Which fails because…


错误:输入 BankAccountParamters不符合协议'Encodable'

error: type 'BankAccountParamters' does not conform to protocol 'Encodable'

注意:由于过滤器不符合 Encodable,因此无法自动合成 Encodable

note: cannot automatically synthesize 'Encodable' because 'Filters' does not conform to 'Encodable'

过滤器显然确实符合 Encodable (至少它对我来说似乎是这样)。

Filters clearly does conform to Encodable (at least it seems that way to me). Is there a way around this?

推荐答案

协议不符合自身?,协议不符合自身或它所继承的
a协议。在您的情况下,过滤器是否符合可编码

As discussed in Protocol doesn't conform to itself?, a protocol does not conform to itself, or to a protocol that it inherits from. In your case, Filters does not conform to Encodable.

可能的解决方案是制作结构BankAccountParamters
协议参数常规:

A possible solution is to make struct BankAccountParamters and protocol Parameters generic:

protocol Filters: Encodable {
    var page: Int { get }
}

protocol Parameters: Encodable {
    associatedtype T: Filters
    var type: String { get }
    var filters: T { get }
}

struct BankAccountFilters: Filters {
    var page: Int
    var isWithdrawal: Bool
}

struct BankAccountParamters<T: Filters>: Parameters {
    let type: String = "Bank"
    var filters: T
}

现在 var个过滤器的类型为 T ,它符合过滤器,然后将其转换为 Encodable

Now var filters has type T, which conforms to Filters and consequently, to Encodable.

这将编译并产生预期的结果:

This compiles and produces the expected result:

let baf = BankAccountFilters(page: 1, isWithdrawal: true)
let bap = BankAccountParamters(filters: baf)

let data = try! JSONEncoder().encode(bap)
print(String(data: data, encoding: .utf8)!)
// {"type":"Bank","filters":{"isWithdrawal":true,"page":1}}

这篇关于协议扩展的可编码(或可编码)不符合它的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆