gpt4 book ai didi

ios - 解码子类时忽略父类(super class)属性

转载 作者:行者123 更新时间:2023-11-28 08:00:33 25 4
gpt4 key购买 nike

我正在尝试制作继承的数据模型,以便使用 JSONDecoder 对其进行解析。

class FirstClass : Codable {
let firstClassProperty: Int
final let arrayOfInts: [Int]
}

class SecondClass : FirstClass {
let secondClassProperty1: Int
let secondClassProperty2: Int

private enum CodingKeys : String, CodingKey {
case secondClassProperty1, secondClassProperty2
}

required init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)

secondClassProperty1 = try container.decode(Int.self, forKey: .secondClassProperty1)
secondClassProperty2 = try container.decode(Int.self, forKey: .secondClassProperty2)

try super.init(from: decoder)
}
}

我将此 JSON 用于 FirstClass:

{
"firstClassProperty": 123,
"arrayOfInts": [
123
]
}

这是SecondClass:

{
"firstClassProperty": {},
"secondClassProperty1": {},
"secondClassProperty2": {}
}

如果关键字 final 在这种情况下不起作用,我如何摆脱子类中的 arrayOfInts 而让它位于父类(super class)中?

这是 Playground .感谢您的回答!

最佳答案

一个快速的技巧是将其声明为可选。例如:

class FirstClas: Codable {
let firstClassProperty: Int
final let arrayOfInts: [Int]?
}

这将自动解决缺少的 arrayOfInts 问题。

手动解决方案。另一种解决方案是自己实现 Decodable 协议(protocol)——就像你在 SecondClass 中所做的那样——并使用 decodeIfPresent 解码 arrayOfInts (否则使用默认值)。


父类(super class)解码。顺便说一下,将 Decoder 转发给父类(super class)的推荐方法是使用 superDecoder() 方法:

...
let superDecoder = try container.superDecoder()
try super.init(from: superDecoder)

关于ios - 解码子类时忽略父类(super class)属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46780681/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com