繁体   English   中英

Swift - 使用 init(来自解码器:)初始化模型对象

[英]Swift - Initialise model object with init(from decoder:)

下面是我的模型结构

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)方法。 在这种情况下创建模型实例的正确方法是什么?

正如Swift 语言指南所写:

Swift 为任何为其所有属性提供默认值的结构或类提供了一个默认初始化器,并且本身不提供至少一个初始化器。

“并且不提供至少一个初始化程序本身”部分在这里至关重要。 由于您要声明一个额外的初始化程序,您应该像这样声明自己的初始化程序:

init(
    totalResults: Int,
    response: String,
    error: String,
    movies: [Movie]
) {
    self.totalResults = totalResults
    self.response = response
    self.error = error
    self.movies = movies
}

或者将Codable一致性移动到扩展中,以便 Swift 可以为您提供默认初始化程序。 这将是一种首选方式(我个人认为,我喜欢将其他协议一致性移至扩展)。

struct MovieResponse {
    var totalResults: Int
    var response: String
    var error: String
    var movies: [Movie]
}

extension MovieResponse: Codable {

    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)!
    }
}

如果您不想使用解码器,则需要添加另一个初始化程序。 当且仅当您不编写自己的初始化程序时,Swift 才会免费为您提供一个。 现在你有了一个,你就失去了自由的一个。

加上另一个:

init() {
    //Your initializer code here
}

如果您尝试使用解码器 init,则需要使用解码器来调用它。 例如,如果它是 Json

@Published var movieObj = try? JSONDecoder().decode(MovieResponse.self, from: <#T##Data#>)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM