【问题标题】:swift 5 abstract network response with codable array带有可编码数组的 swift 5 抽象网络响应
【发布时间】:2020-07-05 08:01:33
【问题描述】:

我有一个模特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
}

但它会抛出错误:

类型“NetworkResponse”不符合协议“Decodable”

类型“NetworkResponse”不符合协议“Encodable”

无法自动合成“Decodable”,因为“[Decodable]”不符合“Decodable”

如何为任何响应创建抽象响应模型?

【问题讨论】:

    标签: swift codable


    【解决方案1】:

    使用泛型:

    struct NetworkResponse<T: Codable>: Codable {
        let rows: [T]
        let total: Int
    }
    
    typealias EmployeeResponse = NetworkResponse<Employee>
    typealias OfficeReponse = NetworkResponse<Office>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-05-31
      • 1970-01-01
      • 2021-01-26
      • 1970-01-01
      • 1970-01-01
      • 2020-03-30
      • 2023-02-17
      • 1970-01-01
      相关资源
      最近更新 更多