类型 'Model' 不符合协议 'Decodable'/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
                    }
                }

错误:

Instance method 'onReceive(_:perform:)' requires that 'TimeModel' conform to 'Publisher'

A @Published 属性 类型,比方说,String,是 Published<String> 类型。显然,该类型不是 Codable.

您可以通过编写自定义编码和解码函数来解决这个问题。那并不难;它只是一些额外的代码行。请参阅 documentation on 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)
    }
}

这个 应该 工作,但我无法真正测试它,因为我不知道你的代码的其余部分。