在 Swift 中甚至可以解码继承吗?
Is Decodable inheritance even possible in Swift?
我通常使用从 Decodable 继承的结构来序列化我从后端提取的 JSON 数据。但是,我有一个应用程序,其中 JSON 有效负载与现有结构相同,只有一些细微差别。因此,我想要一个可解码结构,它继承自另一个可解码结构,如下所示:
class Party: Decodable {
var theme: String
}
class PublicParty : Party {
var address: String = ""
}
但是,当我发送以下 JSON 负载时,只有来自派对 class 的 "theme" 被解码,而来自 PublicParty 的 "address" 仍然是 "":
{
"theme": "Black out or get out",
"address": "404 Mundus, Tabasko Beach 45778 WA"
}
Swift代码:
func test(completion: @escaping(Result<PublicParty, Error>) -> ()) {
guard let url = URL(string: "127.0.0.1:8000/test") else { return }
URLSession.shared.dataTask(with: url) { (data, response, error) in
// handle error
if let error = error {
completion(.failure(error))
return
}
// decode data
do {
let search = try JSONDecoder().decode(PublicParty.self, from: data!)
print(search)
completion(.success(search))
} catch let error {
completion(.failure(error))
}
}.resume()
}
由于我前面没有任何问题 end/back 结束,Swift 甚至允许此功能吗?
这有效:
class Party: Decodable {
var theme: String
}
class PublicParty : Party {
var address: String = ""
required init(from decoder: Decoder) throws {
try super.init(from: decoder)
let values = try decoder.container(keyedBy: CodingKeys.self)
address = try values.decode(String.self, forKey: .address)
}
private enum CodingKeys: String, CodingKey
{
case address
}
}
我通常使用从 Decodable 继承的结构来序列化我从后端提取的 JSON 数据。但是,我有一个应用程序,其中 JSON 有效负载与现有结构相同,只有一些细微差别。因此,我想要一个可解码结构,它继承自另一个可解码结构,如下所示:
class Party: Decodable {
var theme: String
}
class PublicParty : Party {
var address: String = ""
}
但是,当我发送以下 JSON 负载时,只有来自派对 class 的 "theme" 被解码,而来自 PublicParty 的 "address" 仍然是 "":
{
"theme": "Black out or get out",
"address": "404 Mundus, Tabasko Beach 45778 WA"
}
Swift代码:
func test(completion: @escaping(Result<PublicParty, Error>) -> ()) {
guard let url = URL(string: "127.0.0.1:8000/test") else { return }
URLSession.shared.dataTask(with: url) { (data, response, error) in
// handle error
if let error = error {
completion(.failure(error))
return
}
// decode data
do {
let search = try JSONDecoder().decode(PublicParty.self, from: data!)
print(search)
completion(.success(search))
} catch let error {
completion(.failure(error))
}
}.resume()
}
由于我前面没有任何问题 end/back 结束,Swift 甚至允许此功能吗?
这有效:
class Party: Decodable {
var theme: String
}
class PublicParty : Party {
var address: String = ""
required init(from decoder: Decoder) throws {
try super.init(from: decoder)
let values = try decoder.container(keyedBy: CodingKeys.self)
address = try values.decode(String.self, forKey: .address)
}
private enum CodingKeys: String, CodingKey
{
case address
}
}