由于您无法始终控制要使用的API,因此这是一种
Codable通过重写直接解决此问题的简单方法
init(from:):
struct Product : Decodable { // Properties in Swift are camelCased. You can provide the key separately from the property. var manageStock: Bool? private enum CodingKeys : String, CodingKey { case manageStock = "manage_stock" } init(from deprer: Deprer) throws { let container = try deprer.container(keyedBy: CodingKeys.self) do { self.manageStock = try container.depreIfPresent(Bool.self, forKey: .manageStock) } catch DecodingError.typeMismatch { // There was something for the "manage_stock" key, but it wasn't a boolean value. Try a string. if let string = try container.depreIfPresent(String.self, forKey: .manageStock) { // Can check for "parent" specifically if you want. self.manageStock = false } } }}有关更多信息,请参见编码和解码自定义类型。



