如何在读取绑定的JSON数据时使用init(来自解码器:)

如何在读取绑定的JSON数据时使用init(来自解码器:),json,swift,init,decoder,Json,Swift,Init,Decoder,我有一个JSON字典数组,需要对其进行解码以生成数据类型(Hitter),Hitter对象需要保存原始JSON数据,我需要在应用程序的整个生命周期中为Hitter添加属性。我发现我需要使用init(来自解码器:),但是如何正确调用init…我将在联盟结构中存储击球手 struct League { var Hitters: Set<Hitter> func loadHitters() { ...//ingest json from bundle,

我有一个JSON字典数组,需要对其进行解码以生成数据类型(Hitter),Hitter对象需要保存原始JSON数据,我需要在应用程序的整个生命周期中为Hitter添加属性。我发现我需要使用init(来自解码器:),但是如何正确调用init…我将在联盟结构中存储击球手

struct League {
    var Hitters: Set<Hitter>

    func loadHitters() {
        ...//ingest json from bundle, 
           //store decoded Hitter objects in temp array, 
           //then append each item from temp array into League.Hitters set.
    }
}
为了划分,我在扩展中声明CodingKeys和init(解码器:)

extension Hitter {
    enum CodingKeys: String, CodingKey {
        case strPos, OBP, wRAA
    }

    convenience init(from decoder: Decoder) {
        //container links all the CodingKeys and JSONDecoder keys for proper referencing. Returns the data stored in this decoder as represented in a container keyed by the given key type
        let container = try decoder.container(keyedBy: CodingKeys.self)

        let strPos = try container.decode(String.self, forKey: .strPos)
        let OBP = try container.decode(Float.self, forKey: .OBP)
        let wRAA = try container.decode(Float.self, forKey: .wRAA)

        //pass my decoded values via a standard initializer
        self.init(strPos: strPos, OBP: OBP, wRAA: wRAA)
    }

}

只要我通过一个容器显式地链接JSON格式和编码键,这似乎工作得很好。

如果你设计一个结构,你可以免费获得一个memberwise
初始化器
——假设你自己没有定义其他的
初始化器
,但是
结构
自动初始化器是内部的。编写
模块
时,必须生成memeberwise
初始值设定项
,以使其公开

“结构类型的默认成员初始值设定项默认值 如果 结构的任何存储属性都是私有的 初始值设定项的访问级别为内部

与上面的默认初始值设定项一样,如果需要公共结构 在中使用时,要使用成员初始值设定项初始化的类型 另一个模块,必须提供公共成员初始值设定项 将您自己作为类型定义的一部分。”


Swift Docs”“

如果使用JSONDecoder对其进行解码,将自动使用初始化
extension Hitter {
    enum CodingKeys: String, CodingKey {
        case strPos, OBP, wRAA
    }

    convenience init(from decoder: Decoder) {
        //container links all the CodingKeys and JSONDecoder keys for proper referencing. Returns the data stored in this decoder as represented in a container keyed by the given key type
        let container = try decoder.container(keyedBy: CodingKeys.self)

        let strPos = try container.decode(String.self, forKey: .strPos)
        let OBP = try container.decode(Float.self, forKey: .OBP)
        let wRAA = try container.decode(Float.self, forKey: .wRAA)

        //pass my decoded values via a standard initializer
        self.init(strPos: strPos, OBP: OBP, wRAA: wRAA)
    }

}