如何在可解码模型中使用继承
how to use inheritance in decodable model
我从服务器收到了一些 json 结果。他们都有一个共享部分。然后在 results
属性 中,返回值不同。
{
"code": 200,
"status": "Ok"
"data":
{
"count": 3,
"total": 7,
"results": [
{
"id": 43424,
"title": "some title"
}
]
}
}
正如我所说,我所有模型的结构都是相同的。它们仅在 results
上有所不同。我想做的是避免编写冗余代码,并使用继承来创建一个具有所有共享部分的 BaseClass
,我的模型继承这个 BaseClass
。我在 Decodable
模型中看过一些关于继承的教程和帖子,但我仍然不清楚如何实现它。
而不是继承和 类 使用泛型和 结构 因为 Decodable
不支持继承默认。
例如创建一个结构 JSONParser
struct JSONParser<T : Decodable> {
struct ResponseData<U : Decodable> : Decodable {
let total, count : Int
let results : [U]
}
let code : Int
let status : String
let data : ResponseData<T>
init(data: Data) throws {
let decoder = JSONDecoder()
data = try decoder.decode(ResponseData.self, from: data)
}
}
并将其用于包含 id
和 title
的字典
struct Item {
let id : Int
let title : String
}
do {
let jsonParser = try JSONParser<Item>(data: data)
let results = jsonParser.data.results
} catch { print(error) }
我从服务器收到了一些 json 结果。他们都有一个共享部分。然后在 results
属性 中,返回值不同。
{
"code": 200,
"status": "Ok"
"data":
{
"count": 3,
"total": 7,
"results": [
{
"id": 43424,
"title": "some title"
}
]
}
}
正如我所说,我所有模型的结构都是相同的。它们仅在 results
上有所不同。我想做的是避免编写冗余代码,并使用继承来创建一个具有所有共享部分的 BaseClass
,我的模型继承这个 BaseClass
。我在 Decodable
模型中看过一些关于继承的教程和帖子,但我仍然不清楚如何实现它。
而不是继承和 类 使用泛型和 结构 因为 Decodable
不支持继承默认。
例如创建一个结构 JSONParser
struct JSONParser<T : Decodable> {
struct ResponseData<U : Decodable> : Decodable {
let total, count : Int
let results : [U]
}
let code : Int
let status : String
let data : ResponseData<T>
init(data: Data) throws {
let decoder = JSONDecoder()
data = try decoder.decode(ResponseData.self, from: data)
}
}
并将其用于包含 id
和 title
struct Item {
let id : Int
let title : String
}
do {
let jsonParser = try JSONParser<Item>(data: data)
let results = jsonParser.data.results
} catch { print(error) }