不符合哈希协议?

Rah*_*hul 21 ios swift swiftui

我正在尝试根据 JSON 响应创建视图模型,但出现以下错误。

在此输入图像描述

import Foundation
import SwiftUI
    
public class DeclarationViewModel: ObservableObject {
    @Published var description: [DeclarationListViewModel]?
    init() {
        self.description = [DeclarationListViewModel]()
    }
    init(shortDescription: [DeclarationListViewModel]?) {
        self.description = shortDescription
    }
}
    
public class DeclarationListViewModel: ObservableObject, Hashable {
    @Published var yesNo: Bool?
    @Published var title: String?
}
Run Code Online (Sandbox Code Playgroud)

尝试在 foreach 中使用结果

在此输入图像描述

谢谢你的帮助。如果需要更多详细信息,请告诉我。

Art*_*uro 26

删除import SwiftUI尝试不要在 ViewModel 中使用它,除非确实有必要。还要从类声明中删除Hashable,并在其外部创建一个如下所示的扩展:

extension DeclarationListViewModel: Identifiable, Hashable {
    var identifier: String {
        return UUID().uuidString
    }
    
    public func hash(into hasher: inout Hasher) {
        return hasher.combine(identifier)
    }
    
    public static func == (lhs: DeclarationListViewModel, rhs: DeclarationListViewModel) -> Bool {
        return lhs.identifier == rhs.identifier
    }
}
Run Code Online (Sandbox Code Playgroud)

还要记住它的structs存在,它们非常适合定义您的模型。

还有一件事,也许不是有一个可选的布尔值,为什么不用 false 初始化它,并在您的视图或视图模型中,无论您在哪里首先调用它,如果是这种情况,请将其设置为 true。


小智 9

编译器只是通过说来告诉你

在你的类声明中,“,Hashable”,你承诺遵守 Hashable 协议的规则。另外,Hashable 继承自 Equatable 协议。为了遵守 Hashable 的规则,您也表示您同意 Equatable 的规则。协议规则只是您承诺实现的函数和/或您承诺拥有的变量的列表。

在您的情况下,您需要协议的要求: 在此输入图像描述

您需要履行 Hashable 协议的承诺:

在此输入图像描述

您可以通过仔细查看文档来找到此类信息。 https://developer.apple.com/documentation/swift/hashable

在您的情况下,您需要在DeclarationListViewModel中添加两个方法

扩展DeclarationListViewModel { static func ==(lhs:DeclarationListViewModel, rhs:DeclarationListViewModel) {

    return lhs.yesNo == rhs.yesNo &&
           lhs.title == rhs.title
}
Run Code Online (Sandbox Code Playgroud)

}

并可哈希

func hash(into hasher: inout Hasher) {
    hasher.combine(yesNo)
    hasher.combine(title)
}
Run Code Online (Sandbox Code Playgroud)