我正在尝试根据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?
}尝试在foreach中使用result

谢谢你的帮助。如果需要更多细节,请让我知道。
发布于 2021-08-23 14:41:11
编译器只是通过以下方式告诉您这一点
",Hashable“在您的类声明中,您承诺遵守Hashable协议的规则。此外,Hashable继承自协议Equatable。为了遵守Hashable的规则,你也在说你同意Equatable的规则。协议规则只是您承诺实现的函数和/或您承诺拥有的变量的列表。
在您的示例中,您需要对协议equatable满足以下要求:

你需要实现协议Hashable的这个承诺:

您可以通过仔细查看文档来找到此类信息。https://developer.apple.com/documentation/swift/hashable
在本例中,您需要在DeclarationListViewModel中添加两个方法
扩展函数{ static func ==(lhs: DeclarationListViewModel,rhs: DeclarationListViewModel) {
return lhs.yesNo == rhs.yesNo &&
lhs.title == rhs.title
}}
并且是可哈希的
func hash(into hasher: inout Hasher) {
hasher.combine(yesNo)
hasher.combine(title)
}发布于 2021-08-24 10:47:22
删除import SwiftUI尽量不要在ViewModels中使用它,除非确实必要。另外,从类声明中删除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
}
}还要记住,structs是存在的,哈哈,它们对于定义你的模型是很棒的。
还有一件事,也许不是有一个可选的布尔值,为什么不用false初始化它,在你的视图或视图模型中,无论你第一次调用它的地方,如果是这样的话,将它设置为true。
https://stackoverflow.com/questions/68893073
复制相似问题