具有不同值的Swift JSON解码器
我想解码一本不同值的字典。因此,虽然键的类型始终为具有不同值的Swift JSON解码器,swift,jsondecoder,Swift,Jsondecoder,我想解码一本不同值的字典。因此,虽然键的类型始终为字符串,但值将具有相同的超类(如形状),但可能由不同的子类组成(如矩形,圆形)。我希望以后能够检查附加了哪个子类,但到目前为止,我只能使用默认解码到[AttachedObject:Shape] 请参见示例: enum AttachedObject: String, Codable { case chair case lamp case desk } class Shape: Codable { var name:
字符串
,但值将具有相同的超类
(如形状
),但可能由不同的子类组成(如矩形
,圆形
)。我希望以后能够检查附加了哪个子类
,但到目前为止,我只能使用默认解码到[AttachedObject:Shape]
请参见示例:
enum AttachedObject: String, Codable {
case chair
case lamp
case desk
}
class Shape: Codable {
var name: String
init(name: String) {
self.name = name
}
}
class Rectangle: Shape {
var width: Double
var height: Double
init(name: String, width: Double, height: Double) {
self.width = width
self.height = height
super.init(name: name)
}
enum CodingKeys: String, CodingKey {
case width
case height
}
public override func encode(to encoder: Encoder) throws {
try super.encode(to: encoder)
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(self.height, forKey: .height)
}
required public init(from decoder: Decoder) throws {
let values = try decoder.container(keyedBy: CodingKeys.self)
self.width = try values.decode(Double.self, forKey: .width)
self.height = try values.decode(Double.self, forKey: .height)
try super.init(from: decoder)
}
}
class Circle: Shape {
var radius: Double
init(name: String, radius: Double) {
self.radius = radius
super.init(name: name)
}
enum CodingKeys: String, CodingKey {
case radius
}
public override func encode(to encoder: Encoder) throws {
try super.encode(to: encoder)
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(self.radius, forKey: .radius)
}
required public init(from decoder: Decoder) throws {
let values = try decoder.container(keyedBy: CodingKeys.self)
self.radius = try values.decode(Double.self, forKey: .radius)
try super.init(from: decoder)
}
}
class MyRoom: Codable {
public var attachedShapes: [ AttachedObject: Shape ]
enum CodingKeys: String, CodingKey {
case attachedShapes
}
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(self.attachedShapes, forKey: .attachedShapes)
}
required public init(from decoder: Decoder) throws {
let values = try decoder.container(keyedBy: CodingKeys.self)
fatalError("// How to handle the decoding part?")
}
}
我会这样说:
enum ShapeType: String, RawRepresentable, Codable {
// Required for RawRepresentable
static var defaultDecoderValue: ShapeType = .circle
case circle
case rectangle
}
struct Shape: Codable {
let name: String
let width: Double?
let height: Double?
let radius: Double?
let type: ShapeType
}
那么您就不需要任何自定义密钥。您始终可以引用数组中的任何形状,等等。您可以查看ShapeType以查看它是矩形还是圆形。如果需要更改它们,您可以将它们设置为var而不是let,如果您需要一个类,您可以将它们设置为is Class Shape而不是Struct Shape。这并不能解决问题,因为我们只是定义了另一个总体类,之后必须进行整理。这样我们就可以解决问题。此外,随着类和属性数量的增加,这一点也不太合适。我试着使用.nestedUnkeyedContainer(forKey:.attachedShapes)
这样人们可以单独解码,但是这是未知的,因此键值相关性。它将代码从85行减少到15行。从3个类到一个结构。