【发布时间】:2021-07-01 16:19:22
【问题描述】:
下面是我的模型结构
struct MovieResponse: Codable {
var totalResults: Int
var response: String
var error: String
var movies: [Movie]
enum ConfigKeys: String, CodingKey {
case totalResults
case response = "Response"
case error = "Error"
case movies
}
init(from decoder: Decoder) throws {
let values = try decoder.container(keyedBy: CodingKeys.self)
self.totalResults = try values.decodeIfPresent(Int.self, forKey: .totalResults)!
self.response = try values.decodeIfPresent(String.self, forKey: .response)!
self.error = try values.decodeIfPresent(String.self, forKey: .error) ?? ""
self.movies = try values.decodeIfPresent([Movie].self, forKey: .movies)!
}
}
extension MovieResponse {
struct Movie: Codable, Identifiable {
var id = UUID()
var title: String
var year: Int8
var imdbID: String
var type: String
var poster: URL
enum EncodingKeys: String, CodingKey {
case title = "Title"
case year = "Year"
case imdmID
case type = "Type"
case poster = "Poster"
}
}
}
现在在 ViewModel 中,我正在使用以下代码创建此模型的实例
@Published var movieObj = MovieResponse()
但是有一个编译错误说,调用init(from decoder)方法。在这种情况下创建模型实例的正确方法是什么?
【问题讨论】:
-
不相关但强制解开由
decodeIfPresent解码的值是没有意义的。删除IfPresent和结尾的感叹号。如果出现问题,该行将引发错误,而不是引发崩溃。
标签: ios swift jsondecoder