【问题标题】:How to keep a flexible structure when using Codable in Swift在 Swift 中使用 Codable 时如何保持灵活的结构
【发布时间】:2020-04-18 11:04:51
【问题描述】:

我有一个 API 响应结构,代表一个用户对象,如下所示:

{
    "statuscode": 200,
    "response_type": 3,
    "errormessage": null,
    "detailresponse": {
        "id": "2",
        "shopifyautosync": null,
        "platformfeepercentage": null,
        "invited": null,
        "requiresyoutubesocialmediaupdate": 1,
        // Other properties ...
}

我正在使用 JSONDecoder().decode 解码为以下结构:

import Foundation

class Response: Decodable {
    var statuscode: Int?
    var response_type: Int?
    // Other properties
    var detailresponse: User?
}

import Foundation

class User: Codable {
    var id: String?
    var street: String?
    var supporturl: String?
    var verifiedaccount: Int?
    var showfeatureupdatemodal: Int?
    var admin: Int?
    var email: String?
    // Other properties
}

然后我是这样解码的:

let response = try JSONDecoder().decode(Response.self, from: jsonData)

我现在的主要问题是 Response 类的 detailresponse 属性硬连接到 User 结构。但是,我的设置需要一点灵活性, 因为 detailresponse 在调用不同的端点时当然会携带其他数据结构(例如,合作对象而不是用户对象)。

有没有一种优雅的方法来保持 Response 类中的 detailresponse 灵活而不是硬连接它?或者是一个更好的解决问题的方法?

【问题讨论】:

    标签: swift codable jsondecoder


    【解决方案1】:

    你需要使用泛型

    class Response<T:Decodable>: Decodable {
        var statuscode: Int?
        var response_type: Int?
        // Other properties
        var detailresponse: T?
    }
    

    然后

    let response = try JSONDecoder().decode(Response<User>.self, from: jsonData)
    

    【讨论】:

      【解决方案2】:

      这是泛型的一个用例:

      class Response<T: Decodable>: Decodable {
         var statuscode: Int?
         var response_type: Int?
         // Other properties
         var detailresponse: T?
      }
      

      请注意,几乎没有理由使属性可变。他们应该是let。此外,struct 在这里可能是更好的选择。而且我认为应该减少可选项,因为这应该是成功的响应。

      【讨论】:

      • 非常感谢您的及时帮助!你能告诉我为什么一个结构会比这里的类更好吗?
      • @BernhardEngl 它是轻量级的。我总是更喜欢struct,除非我需要类语义或继承,尤其是对于不可变数据类型。
      • 谢谢,明白了。还尝试遵循您关于使属性不可变的建议。但是,一旦我将其中一个声明为“let”,我的 init 方法就会出现错误:“从初始化程序返回而不初始化所有存储的属性”。不知道如何运送。
      猜你喜欢
      • 1970-01-01
      • 2019-05-12
      • 1970-01-01
      • 1970-01-01
      • 2019-09-27
      • 2021-07-06
      • 1970-01-01
      • 2022-07-20
      • 1970-01-01
      相关资源
      最近更新 更多