Ниже представлена структура моей модели
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
и восклицательный знак в конце. Вместо того, чтобы вызвать сбой, строка выдаст ошибку, если что-то пойдет не так.