我的可编码观察对象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()
}