我是 SwiftUI 新手,正在尝试一些东西。 我有一个列表,它是由数组构建的。我想根据单击的行创建一个导航。所以我构建了一个具有以下内容的结构:
struct DiscoverItem: Hashable, Equatable {
var name: String
var destination: AnyView
}
let arr = [
DiscoverItem(name: "Catalogus", destination: AnyView(ProductList(products: []))),
DiscoverItem(name: "Locations", destination: AnyView(LocationList()))
]
但是 Xcode 说
Type 'DiscoverItem' does not conform to protocol 'Equatable'
我该如何解决这个问题,或者哪种方法是正确的方法?
最佳答案
这是由于 AnyView
禁用了自动遵守这些协议(protocol)(因为不符合这些协议(protocol))。
这是可能的解决方案:
struct DiscoverItem: Hashable, Equatable {
static func == (lhs: DiscoverItem, rhs: DiscoverItem) -> Bool {
lhs.id == rhs.id
}
func hash(into hasher: inout Hasher) {
hasher.combine(id)
hasher.combine(name)
}
let id = UUID()
var name: String
var destination: AnyView
}
关于带有 AnyView 的 SwiftUI 对象数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64051363/