【问题标题】:Type 'Model' does not conform to protocol 'Decodable'/Encodable类型“模型”不符合协议“可解码”/可编码
【发布时间】:2020-11-27 17:17:56
【问题描述】:

我不知道如何解决这个错误。

如果我删除 @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' 符合“出版商”

【问题讨论】:

  • 很难理解您要使用此代码实现的目标,因为您将许多概念混合在一起。如果我看到Codable,我认为您需要从某种持久层序列化/反序列化此对象,但随后我看到SwiftUI 相关协议是表示层问题,并且您也在内部使用DispatchQueue.main。您是否从此类外部动态更改nometime?你什么时候打电话给aggiornaUI
  • @FabioFelici 目前尚未使用 updateUI,稍后当我实现从我的应用程序修改数据的可能性时,我需要它。这段代码我用它作为模型,在哪里。在我的 DataManager 中,我将把我的数据保存在一个数组中。然后我从我需要的各种视图中回忆我需要的数据

标签: ios encoding swiftui decodable


【解决方案1】:

类型为String@Published 属性的类型为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)
    }
}

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

【讨论】:

  • 好的,谢谢我现在检查,但错误仍然存​​在我用错误更新帖子
  • @user12147631 看起来您还有另一个与问题无关的错误。请创建另一个帖子来解释您的问题。
猜你喜欢
  • 1970-01-01
  • 2020-10-07
  • 1970-01-01
  • 2021-04-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多