如何使' ObservableObject '与' @Published '属性'可编码' ?



我的可编码观察对象Thing编译:

class Thing: Codable, ObservableObject {
var feature: String
}

feature包裹在@Published中,尽管没有:

class Thing: Codable, ObservableObject {
@Published var feature: String
}
🛑 Class 'Thing' has no initializers
🛑 Type 'Thing' does not conform to protocol 'Decodable'
🛑 Type 'Thing' does not conform to protocol 'Encodable'

显然Codable一致性不能再合成了,因为@Published不知道如何编码/解码它的wrappedValue(因为它不符合Codable,即使它的包装值)?

好吧,我会让它知道怎么做的!

extension Published: Codable where Value: Codable {
public func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
try container.encode(wrappedValue) // 🛑 'wrappedValue' is unavailable: @Published is only available on properties of classes
}
public init(from decoder: Decoder) throws {
var container = try decoder.singleValueContainer()
wrappedValue = try container.decode(Value.self) // 🛑 'wrappedValue' is unavailable: @Published is only available on properties of classes
}
}

那么悲伤,那么痛苦,那么悲伤!😭

在不定义encode(to:)init(from:)的情况下,如何轻松添加Codable合成(或类似)?

我不知道你为什么要这样做,我认为你应该编码结构,而不是发布的类。像这样:

struct CodableStruct: Codable {
var feature1: String = ""
var feature2: Int = 0
}
class Thing: ObservableObject {
@Published var features: CodableStruct = .init()
}

相关内容

  • 没有找到相关文章

最新更新