![](/img/trans.png)
[英]Type 'PlayerData' does not conform to protocol 'Decodable' and 'Encodable'
[英]Type 'Model' does not conform to protocol 'Decodable'/Encodable
我不知道如何解决这个错误。
如果我删除@Published,它会正确编译所有内容,但我无法实时查看单元格中的数据。 阅读我看到我需要带有@Published
的var
import SwiftUI
import Combine
class TimeModel: Codable, Identifiable, ObservableObject {
@Published var id: UUID = UUID()
@Published var nome : String
@Published var time : String
func aggiornaUI() {
DispatchQueue.main.async {
self.objectWillChange.send()
}
}
init(nome: String, time: String) {
self.nome = nome
self.time = time
}
}
更新:好的,谢谢我现在检查,但错误仍然存在
HStack {
Text("\(timeString(from: Int(TimeInterval(remainingSeconds))))")
.onReceive(timer) { _ in
if isCounting && remainingSeconds > 0 {
remainingSeconds -= 1
}
}
错误:
实例方法 'onReceive(_:perform:)' 要求 'TimeModel' 符合 'Publisher'
具有类型的@Published
属性,比如String
,属于Published<String>
类型。 显然,这种类型不是Codable
。
您可以通过编写自定义编码和解码函数来解决这个问题。 这并不难; 它只是一些额外的代码行。 有关示例,请参阅Codable
上的文档。
这是您的案例的示例:
class TimeModel: Codable, Identifiable, ObservableObject {
@Published var id: UUID = UUID()
@Published var nome : String
@Published var time : String
func aggiornaUI() {
DispatchQueue.main.async {
self.objectWillChange.send()
}
}
init(nome: String, time: String) {
self.nome = nome
self.time = time
}
enum CodingKeys: String, CodingKey {
case id
case nome
case time
}
func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(id, forKey: .id)
try container.encode(nome, forKey: .nome)
try container.encode(time, forKey: .time)
}
required init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
id = try container.decode(UUID.self, forKey: .id)
nome = try container.decode(String.self, forKey: .nome)
time = try container.decode(String.self, forKey: .time)
}
}
这应该可行,但我无法真正测试它,因为我不知道您的代码的 rest。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.