【发布时间】:2021-06-17 20:07:04
【问题描述】:
我有一个这样的结构
struct SymbolView: View, Identifiable {
let id = UUID()
var name:String
var code:String
@State var position = CGPoint(x:100, y:100)
@State var scale = CGFloat(1)
}
我需要使用 Codable 将其转换为 JSON,所以我这样做了
extension SymbolView: Codable{
private enum CodingKeys: String, CodingKey {
case name
case code
case position
case scale
}
public func encode(to encoder:Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
do {
try container.encode(self.name, forKey: .name)
try container.encode(self.code, forKey: .code)
try container.encode(self.position, forKey: .position)
try container.encode(self.scale, forKey: .scale)
} catch (let error) {
print(error.localizedDescription)
}
}
}
错误:无法自动合成 'Decodable',因为 'State' 不符合 'Decodable' 并且该点的错误相同。
这里的问题似乎是两个属性都是@State。
我该如何解决?
【问题讨论】:
-
我建议将
id, name, code, position, scale封装到他们自己的可编码struct中,并将其用作SymbolView上的单个@State属性。然后,只需对模型进行编码/解码,而不是尝试对View进行编码/解码。 -
我这样做了,问题仍然存在。您可以通过示例发布答案吗?谢谢
-
用我的想法添加的示例以及对您原始想法的修改