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
.
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
}
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}}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…