swift 5 具有可编码数组的抽象网络响应
swift 5 abstract network response with codable array
我有一个模型 Employee
& Office
:
struct Employee: Codable {
let id: Int
let firstName: String
let lastName: String
}
struct Office: Codable {
let id: Int
let name: String
}
根据要求要求员工或办公室机构:
{
total: Int
rows: [Employee]
}
or
{
total: Int
rows: [Office]
}
为此,我想创建如下抽象模型:
struct NetworkResponse: Codable {
let rows: [Codable]
let total: Int
}
但它抛出错误:
Type 'NetworkResponse' does not conform to protocol 'Decodable'
Type 'NetworkResponse' does not conform to protocol 'Encodable'
Cannot automatically synthesize 'Decodable' because '[Decodable]' does not conform to 'Decodable'
如何为任何响应创建抽象响应模型?
使用泛型:
struct NetworkResponse<T: Codable>: Codable {
let rows: [T]
let total: Int
}
typealias EmployeeResponse = NetworkResponse<Employee>
typealias OfficeReponse = NetworkResponse<Office>
我有一个模型 Employee
& Office
:
struct Employee: Codable {
let id: Int
let firstName: String
let lastName: String
}
struct Office: Codable {
let id: Int
let name: String
}
根据要求要求员工或办公室机构:
{
total: Int
rows: [Employee]
}
or
{
total: Int
rows: [Office]
}
为此,我想创建如下抽象模型:
struct NetworkResponse: Codable {
let rows: [Codable]
let total: Int
}
但它抛出错误:
Type 'NetworkResponse' does not conform to protocol 'Decodable'
Type 'NetworkResponse' does not conform to protocol 'Encodable'
Cannot automatically synthesize 'Decodable' because '[Decodable]' does not conform to 'Decodable'
如何为任何响应创建抽象响应模型?
使用泛型:
struct NetworkResponse<T: Codable>: Codable {
let rows: [T]
let total: Int
}
typealias EmployeeResponse = NetworkResponse<Employee>
typealias OfficeReponse = NetworkResponse<Office>