【发布时间】:2022-01-18 15:07:47
【问题描述】:
我有一个 API 响应返回一个类型不一致的 JSON 字段。因此,我去https://www.quicktype.io寻求帮助并找到了一个模型。
这是我遇到问题的模型部分:
struct MyModel: Codable {
let id: ID?
}
enum ID: Codable {
case integer(Int)
case string(String)
init(from decoder: Decoder) throws {
let container = try decoder.singleValueContainer()
if let x = try? container.decode(Int.self) {
self = .integer(x)
return
}
if let x = try? container.decode(String.self) {
self = .string(x)
return
}
throw DecodingError.typeMismatch(ID.self, DecodingError.Context(codingPath: decoder.codingPath, debugDescription: "Wrong type for ID"))
}
func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
switch self {
case .integer(let x):
try container.encode(x)
case .string(let x):
try container.encode(x)
}
}
}
我有一个完全解码的响应,当我尝试打印该值时,我得到如下信息:
Optional(MyApp.ID.integer(27681250))
或
Optional(MyApp.ID.string(27681250))
我这样做是:
print(modelData?.id)
我想访问我得到的确切值,但我无法这样做。 我曾尝试将其转换为其他类型,但没有帮助。 任何帮助表示赞赏。谢谢。
【问题讨论】:
-
你想如何访问它,作为一个字符串或一个整数,或者你只是想访问 id 值本身?尽量避免将自定义类型命名为与内置类型相同。
Data和ID都已在 swift(Foundation 框架)中使用。 -
我只是在这里这样命名它,而不是在我的代码中。我已将名称编辑回其他内容。感谢您的宝贵时间。
-
好的,很好。当您将 id 作为字符串获取时,该字符串是否总是由数字组成?如果是这样,您可以简化您的解决方案。
-
我希望就是这样。我使用的 API 仅返回数字为
Int或String或有时返回带有字母数字值的String。如果我得到一个字符串,我需要检查它是否只是我已经处理过的数字。 -
好吧,我只是想,如果只是数字,我会在 MyModel 中将
id设为 Int 类型,并在 `init(from:) 中处理转换并跳过这个额外的枚举。