问题描述
有没有办法将 Decodable
与注入的属性一起使用?
final class score: Decodable {
let value: Int?
let uniqueId: String
convenience init(from decoder: Decoder/*,uniqueId: String*/) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
try container.decodeIfPresent(Int.self,forKey: .value).flatMap { value = $0 }
// self.uniqueId = uniqueId
[... other properties parsing ...]
}
}
示例调用:
final class Exam {
let identifier: Int
let scores: [score]
convenience init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
identifier = try container.decode(Int.self,forKey: .identifier)
scores = try container.decode([score].self,forKey: .scores)
// I need to pass Exam's identifier to `score` on init,because it will generate score's `uniqueId `
[... other properties parsing ...]
}
}
这将以缺少 uniqueId
的错误结束,我在 init 之后需要它,但它不在 JSON 中。由于它是标识符,因此将其设为可选并设置在外部并不是正确的处理方式。
我很想按照上面评论的方式注入它,但是怎么做?
解决方法
无法扩展初始化程序,因为它是间接调用的,并且没有提供 API 来扩展它。因此,有几种方法可以绕过它:
- BEST:如果可能,将值注入解码器的
userInfo
。 - 为响应创建单独的类并为模型单独创建。下面的例子。
- 使用普通的
JSONSerialization
而不是Decodable
。 - 正如@JoakimDanielson 建议的那样,在默认初始化程序中创建随机标识符。问题在于它不可重现,因此如果您将其保存到数据库中,您将始终覆盖数据,因为每次解析的 ID 都不同。
方法 2 的示例:
final class ScoreResponse: Decodable {
let value: Int?
convenience init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
try container.decodeIfPresent(Int.self,forKey: .value).flatMap { value = $0 }
[... other properties parsing ...]
}
}
final class Score {
let value: Int?
let uniqueId: String
convenience init(from response: ScoreResponse,uniqueId: String) {
self.value = response.value // etc with other properties
self.uniqueId = uniqueId
}
}
final class Exam: Decodable {
let identifier: String
let scores: [Score] = []
convenience init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
identifier = try container.decode(String.self,forKey: .identifier)
try container.decodeIfPresent([ScoreResponse].self,forKey: .scores).forEach {
scores.append({ Score(from: $0,uniqueId: identifier) })
}
}