Codable 中的多种类型
我使用的 API 可以根据项目的不同返回一个 Bool
或 Int
一个值。我不熟悉如何处理 Codable
数据中一个值的不同类型。额定键可以是对象或布尔值,只是不确定如何正确处理它而不出现 typeMismatch
错误。这是我第一次使用 API 遇到这种情况。
{"id":550,"favorite":false,"rated":{"value":9.0},"watchlist":false}
{“id":405,"favorite":false,"rated":false,"watchlist":false}
struct AccountState: Codable {
let id: Int?
let favorite: Bool?
let watchlist: Bool?
let rated: Rated?
}
struct Rated : Codable {
let value : Int? // <-- Bool or Int
}
I'm using an API which can either return a Bool
or a Int
for one value depending on the item. I'm not familiar with how to handle different types for one value in my Codable
data. The rated key can either be an object or bool, just unsure how to handle this correctly without getting a typeMismatch
error. This is my first time encountering this using an API.
{"id":550,"favorite":false,"rated":{"value":9.0},"watchlist":false}
{“id":405,"favorite":false,"rated":false,"watchlist":false}
struct AccountState: Codable {
let id: Int?
let favorite: Bool?
let watchlist: Bool?
let rated: Rated?
}
struct Rated : Codable {
let value : Int? // <-- Bool or Int
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我绝对同意@vadian。您拥有的是可选的评级。在我看来,这是使用 propertyWrapper 的完美场景。这将允许您将此 Rated 类型与任何模型一起使用,而无需为每个模型手动实现自定义编码器/解码器:
用法:
这将打印:
I definitely agree with @vadian. What you have is an optional rating. IMO this is a perfect scenario for using a propertyWrapper. This would allow you to use this Rated type with any model without having to manually implement a custom encoder/decoder to each model:
Usage:
This would print:
我的建议是实现
init(from detector
),将erated
声明为可选的Double
并解码Dictionary
或 – if这会失败 - 键erated
的Bool
在前一种情况下erated
设置为 Double 值,在后一种情况下它设置为 < code>nil的行 。
else
范围内的Bool
甚至可以省略。My suggestion is to implement
init(from decoder
, declarerated
as optionalDouble
and decode aDictionary
or – if this fails – aBool
for keyrated
. In the former caserated
is set to the Double value, in the latter case it's set tonil
.The line to decode
Bool
in theelse
scope can even be omitted.这是一种简单的方法(很长,但很容易理解)
额定
可以是Bool
或具有Double
作为值)AccountState
格式来自 API 的数据
--转换-->步骤1的结构
--convert-->第 2 步的结构
here is an easy way to do it (it's long, but easy to understand)
rated
can beBool
or hasDouble
as value)AccountState
which can hold both kind of formatdata from API
--convert-->structs of Steps 1
--convert-->struct of Step 2