【发布时间】:2023-03-06 20:32:01
【问题描述】:
在 SwiftUI beta 5 中,Apple 引入了 @Published 注解。此注释当前阻止此类符合 Codable 协议。
我怎样才能遵守这些协议,以便我可以将这个类编码和解码为 JSON?您现在可以忽略 image 属性。
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
}
}
}
【问题讨论】:
-
您是否尝试过自己调用 objectWillChange.send() ?如果您不想这样做,那么使用自定义 init(from:) 应该可以解决问题。