我有一个API,有时会将JSON中的特定键作为Int返回,有时它将返回与String相同的键,我通过创建枚举IntOrString解决了这个问题。现在的问题是,当我调用API来更新这些特定键的标签时,类型是错误的。
然后我得到的错误无法将Double类型转换为DoubleOrString类型
enum DoubleOrString: Codable {
case double(Double)
case string(String)
init(from decoder: Decoder) throws {
let container = try decoder.singleValueContainer()
do {
self = try .double(container.decode(Double.self))
} catch DecodingError.typeMismatch {
do {
self = try .string(container.decode(String.self))
} catch DecodingError.typeMismatch {
throw DecodingError.typeMismatch(
DoubleOrString.self,
DecodingError.Context(
codingPath: decoder.codingPath,
debugDescription: "Encoded payload conflicts with expected type, (Double or String)"
)
)
}
}
}
func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
switch self {
case .double(let double):
try container.encode(double)
case .string(let string):
try container.encode(string)
}
}
}
降低这是我更新标签的地方
self.ageLabel.text = "\(pData.info.detailedInfo?.ageNumber ?? 0.0)"
首先,我认为您应该决定是否真的想在整个计划中将其作为DoubleOrString
。你需要跟踪区别吗?或者你可以修改你的解码器,以使其成为双倍?您的内部数据模型不必重新创建JSON中的每个错误。
如果你想保持枚举,那么我认为你正在寻找的东西是这样的:
extension DoubleOrString {
var doubleValue: Double? {
switch self {
case .double(let double): return double
case .string(let string): return Double(string)
}
}
}
self.ageLabel.text = "\(pData.info.detailedInfo?.ageNumber.doubleValue ?? 0.0)"
(当然,这里的首选解决方案是更正JSON,以便返回一致的类型。我认识到这并不总是一个可用的选项。)
如果你想消除DoubleOrString,这通常是一个好主意,那么在你的结构中向上移动一个级别,并以这种方式解码age
:
guard let age = try
(try? container.decode(Double.self, forKey: .age)) ??
Double(container.decode(String.self, forKey: .age))
else {
throw DecodingError.typeMismatch(Double.self,
DecodingError.Context(
codingPath: decoder.codingPath,
debugDescription: "Encoded payload conflicts with expected type, (Double or String)"))
}
self.age = age
这会尝试将其解码为double,如果失败,则会尝试转换字符串值。如果缺少密钥,这仍将有助于抛出正确的错误,而不需要一堆do / catch块。
如果你有很多这个,你可以这样包装:
struct JSONDouble: Codable {
let value: Double
init(from decoder: Decoder) throws {
let container = try decoder.singleValueContainer()
guard let value = try
(try? container.decode(Double.self)) ??
Double(container.decode(String.self))
else {
throw DecodingError.typeMismatch(Double.self,
DecodingError.Context(
codingPath: decoder.codingPath,
debugDescription: "Encoded payload conflicts with expected type, (Double or String)"))
}
self.value = value
}
}
那你的解码逻辑就是:
self.age = try container.decode(JSONDouble.self, forKey: .age).value