Swift Codable初始化 [英] Swift Codable init

查看:813
本文介绍了Swift Codable初始化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在Swift Coding/Encoding功能完成对JSON的解码后做一些初始化逻辑.

I would like to do some initialization logic after the Swift Coding/Encoding feature has finished decoding a JSON.

struct MyStruct: Codable {
    let id: Int 
    var name: String

    init() {
       name = "\(id) \(name)" 
    }
}

但是我得到了编译器错误:

But I get the compiler error:

Return from initializer without initializing all stored properties

这对我很清楚,因为init()希望我初始化所有属性.但是添加具有所有必需属性的init()并不能解决问题,因为当Codable插入时,该初始化器不会被调用(!):

Which is clear to me because init() wants me to initialise all properties. But adding an init() with all needed properties also doesn't solve it because this initializer is not called(!) when Codable kicks in:

init(id: Int, name: String) {
    // This initializer is not called if Decoded from JSON!
    self.id = id 
    self.name = "\(id) \(name)" 
}

尽管如此-在解码完成后,是否有一种方法可以执行一些初始化逻辑,而无需为每个属性手动进行所有解码?因此,无需每次都执行init(from decoder: Decoder).在这个简短的示例中,我只有两个简单的属性,但是生产代码包含成千上万个属性.

Nevertheless - is there a way to do some initialisation logic after the Decoding has finished but without doing all the decoding manually for each property? So without implementing every time init(from decoder: Decoder). In this short example I have just two simple properties but production code consists of thousands of them.

谢谢.

推荐答案

您可以免费获得所有内容但标准化,或者必须编写自定义初始化程序,例如

Either you get everything for free but standardized or you have to write a custom initializer like

struct MyStruct: Codable  {

    let id: Int 
    var name: String

    init(from decoder: Decoder) throws {
        let container = try decoder.container(keyedBy: CodingKeys.self)
        id = try container.decode(Int.self, forKey: .id)
        let decodedName = try container.decode(String.self, forKey: .name)
        name = "\(id) \(decodedName)" 
    }
}

您可以实现init(),但这独立于解码功能而起作用,并且您必须为所有非可选属性分配默认值,这就是错误的意思.

You can implement init() but this works independent of the decoding functionality and you have to assign a default value to all non-optional properties, that's what the error says.

这篇关于Swift Codable初始化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆