gpt4 book ai didi

ios - Swift:模板定义中的常量

转载 作者:行者123 更新时间:2023-11-28 11:33:36 25 4
gpt4 key购买 nike

我正在与喜欢将 json 主体封装在另一个对象(例如数据)中的后端开发人员合作:

例子:

GET: /user/current:

{
data: {
firstName: "Evan",
lastName: "Stoddard"
}
}

我只想对响应调用 json decode 以获得我创建的用户结构,但添加的数据对象需要另一个结构。为了解决这个问题,我创建了一个通用模板类:

struct DecodableData<DecodableType:Decodable>:Decodable {

var data:DecodableType

}

现在我可以获取我的 json 负载,如果我想获取一个用户结构,只需获取我的模板的数据属性:

let user = JSONDecoder().decode(DecodableData<User>.self, from: jsonData).data

这一切都很好,但有时候,键 data 并不总是 data

我觉得这很可能是相当微不足道的事情,但有没有一种方法可以在我的模板定义中添加一个参数,这样我就可以更改枚举编码键,因为该数据键可能会发生变化?

像下面这样的东西?

struct DecodableData<DecodableType:Decodable, Key:String>:Decodable {

enum CodingKeys: String, CodingKey {
case data = Key
}

var data:DecodableType

}

这样我就可以传入目标可解码类以及封装该对象的 key 。

最佳答案

无需编码键。相反,您需要一个简单的容器,将 JSON 解析为具有一对键值对的字典,并丢弃键。

struct Container<T>: Decodable where T: Decodable {
let value: T

init(from decoder: Decoder) throws {
let container = try decoder.singleValueContainer()
let dict = try container.decode([String: T].self)

guard dict.count == 1 else {
throw DecodingError.dataCorruptedError(in: container, debugDescription: "expected exactly 1 key value pair, got \(dict.count)")
}

value = dict.first!.value
}
}

如果 JSON 为空或有多个键值对,则会引发异常。

假设一个简单的结构如

struct Foo: Decodable, Equatable {
let a: Int
}

无论 key 如何,您都可以解析它:

let foo1 = try! JSONDecoder().decode(
Container<Foo>.self,
from: #"{ "data": { "a": 1 } }"#.data(using: .utf8)!
).value

let foo2 = try! JSONDecoder().decode(
Container<Foo>.self,
from: #"{ "doesn't matter at all": { "a": 1 } }"#.data(using: .utf8)!
).value

foo1 == foo2 // true

这也适用于以 null 作为值的 JSON 响应,在这种情况下,您需要将其解析为您的类型的可选项:

let foo = try! JSONDecoder().decode(
Container<Foo?>.self,
from: #"{ "data": null }"#.data(using: .utf8)!
).value // nil

关于ios - Swift:模板定义中的常量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56225858/

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