gpt4 book ai didi

swift 4 Codable - 如果有字符串或字典如何解码?

转载 作者:可可西里 更新时间:2023-11-01 01:07:49 25 4
gpt4 key购买 nike

我有这样的结构:

struct OrderLine: Codable{
let absUrl: String?
let restApiUrl : String?
let description : String?
let quantity : Int?
let subscription: Subs?
let total: Double?
}

struct Subs: Codable{
let quantity: Int?
let name: String?
}

一些OrderLine在服务器响应中有

"subscription": {
"quantity": 6,
"name": "3 Months"
},

但有时它有 String 类型:

"subscription": "",

没有 subscription 一切正常,但是我有一个错误

CodingKeys(stringValue: "subscription", intValue: nil)], 
debugDescription: "Expected to decode Dictionary<String, Any>
but found a string/data instead.", underlyingError: nil)

所以我的问题是 - 我如何解码或到 String?"",或到 Subs? 而没有任何错误?附:如果我只像 String? 一样对其进行解码,则会出现错误 debugDescription: "Expected to decode String but found a dictionary instead.", underlyingError: nil)

最佳答案

您只需自己实现 init(from:) 并尝试将 subscription 键的值解码为 Dictionary 表示 Subs 并作为 String

struct OrderLine: Codable {
let absUrl: String?
let restApiUrl : String?
let description : String?
let quantity : Int?
let subscription: Subs?
let total: Double?

private enum CodingKeys: String, CodingKey {
case absUrl, restApiUrl, description, quantity, subscription, total
}

init(from decoder:Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
self.absUrl = try container.decodeIfPresent(String.self, forKey: .absUrl)
self.restApiUrl = try container.decodeIfPresent(String.self, forKey: .restApiUrl)
self.description = try container.decodeIfPresent(String.self, forKey: .description)
self.quantity = try container.decodeIfPresent(Int.self, forKey: .quantity)
self.total = try container.decodeIfPresent(Double.self, forKey: .total)
if (try? container.decodeIfPresent(String.self, forKey: .subscription)) == nil {
self.subscription = try container.decodeIfPresent(Subs.self, forKey: .subscription)
} else {
self.subscription = nil
}
}
}

关于swift 4 Codable - 如果有字符串或字典如何解码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54077932/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com