代码之家  ›  专栏  ›  技术社区  ›  Coddo

SwiftUI Swift-类型不符合协议“Equatable”

  •  -1
  • Coddo  · 技术社区  · 12 月前
    import SwiftUI
    
    struct MemeModel: Codable {
        var memeid: Int
        var title: String
        var pic: String
    }
    
    struct DataForGalleryShow: Hashable {
        var galleryMemes: [MemeModel]
        var category: String
    }
    
    struct NavStack: View {
       
        @State private var path = NavigationPath()
        
        var body: some View {
            NavigationStack {
                ZStack {
                    Text("main")
                }
                .navigationDestination(for: DataForGalleryShow.self){ selection in
                    GalleryShow(path: self.$path,
                        galleryMemes: selection.galleryMemes,
                        category: selection.category)
                }
            }
        }
    }
    
    struct GalleryShow: View {
    
        @Binding var path: NavigationPath
        var galleryMemes: [MemeModel]
        var category: String
        
        var body: some View {
            ZStack(){
                Text("bla")
            }
        }
    }
    

    我收到错误:

    Type 'DataForGalleryShow' does not conform to protocol 'Equatable'
    

    当我使用“修复”时,会出现以下内容:

    struct DataForGalleryShow: Hashable {
        static func == (lhs: DataForGalleryShow, rhs: DataForGalleryShow) -> Bool {
            <#code#>
        }
        
        var galleryMemes: [MemeModel]
        var category: String
    }
    

    我不知道该怎么办,请帮帮我。

    我不会改变任何东西 galleryMemes 但只传递此数据,以后不进行编辑,但是 MemeModel 仍然需要 codable 对于其他任务,只是不在 DataForGalleryShow ,在这里,如果可能的话,它可以转换为hashable,这样一切都能正常工作

    1 回复  |  直到 12 月前
        1
  •  0
  •   ITGuy    12 月前

    你需要做的就是制作 MemeModel 符合 Hashable 协议。编译器将为您完成其余的工作:

    struct MemeModel: Codable, Hashable {
        let memeid: Int
        let title: String
        let pic: String
    }
    

    编译器自动生成必要的 Hashable 方法论 DataForGalleryShow (以及 MemeModel )如果它的所有属性都满足 Hashable 协议。

    只有当编译器无法生成方法时,才需要手动实现这些方法。