[英]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.