首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >不符合hashable协议?

不符合hashable协议?
EN

Stack Overflow用户
提问于 2021-08-23 12:52:42
回答 2查看 929关注 0票数 1

我正在尝试根据JSON响应创建视图模型,但是得到了下面的错误。

代码语言:javascript
复制
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

谢谢你的帮助。如果需要更多细节,请让我知道。

EN

回答 2

Stack Overflow用户

发布于 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) {

代码语言:javascript
复制
    return lhs.yesNo == rhs.yesNo &&
           lhs.title == rhs.title
}

}

并且是可哈希的

代码语言:javascript
复制
func hash(into hasher: inout Hasher) {
    hasher.combine(yesNo)
    hasher.combine(title)
}
票数 1
EN

Stack Overflow用户

发布于 2021-08-24 10:47:22

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

代码语言:javascript
复制
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。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/68893073

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档