所有的美好的一天! 我在Swift中使用了最近的Decodable,但我有一个小问题: 在我的json中,我有一个可以是字符串或整数的类的属性。实际上,我已经构建了这个很好的作品:
public enum JSONValue: Decodable {
case string(String)
case int(Int)
public init(from decoder: Decoder) throws {
let container = try decoder.singleValueContainer()
guard let value = ((try? container.decode(String.self)).map(JSONValue.string))
.or((try? container.decode(Int.self)).map(JSONValue.int))
else {
throw DecodingError.typeMismatch(JSONValue.self, DecodingError.Context(codingPath: container.codingPath, debugDescription: "Not a JSON"))
}
self = value
}
}
extension Optional {
func or(_ other: Optional) -> Optional {
switch self {
case .none: return other
case .some: return self
}
}
}
但是当我得到 JSONValue枚举的值时,例如:
// for int (I WANT ONLY 9)
// for string (I WANT ONLY "9")