本文介绍了如何使ObservableObject符合Codable协议?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在SwiftUI beta 5中,苹果引入了@Published注释。该注释当前阻止此类符合Codable协议。

In SwiftUI beta 5, Apple introduced the @Published annotation. This annotation is currently blocking this class from conforming to the Codable protocols.

如何遵守这些协议,以便可以将此类编码和解码为JSON?您现在可以忽略image属性。

How can I conform to these protocols so I can encode and decode this class to JSON? You can ignore the image property for now.

class Meal: ObservableObject, Identifiable, Codable {

    enum CodingKeys: String, CodingKey {
        case id
        case name
        case ingredients
        case numberOfPeople
    }

    var id = Globals.generateRandomId()
    @Published var name: String = "" { didSet { isInputValid() } }
    @Published var image = Image("addImage")
    @Published var ingredients: [Ingredient] = [] { didSet { isInputValid() } }
    @Published var numberOfPeople: Int = 2
    @Published var validInput = false

    func isInputValid() {
        if name != "" && ingredients.count > 0 {
            validInput = true
        }
    }
}


推荐答案

添加 init() encode()类的方法:

required init(from decoder: Decoder) throws {
    let values = try decoder.container(keyedBy: CodingKeys.self)

    id = try values.decode(Int.self, forKey: .id)
    name = try values.decode(String.self, forKey: .name)
    ingredients = try values.decode([Ingredient].self, forKey: .ingredients)
    numberOfPeople = try values.decode(Int.self, forKey: .numberOfPeople)
}

func encode(to encoder: Encoder) throws {
    var container = encoder.container(keyedBy: CodingKeys.self)
    try container.encode(id, forKey: .id)
    try container.encode(name, forKey: .name)
    try container.encode(ingredients, forKey: .ingredients)
    try container.encode(numberOfPeople, forKey: .numberOfPeople)
}

这篇关于如何使ObservableObject符合Codable协议?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-28 04:02