iosswiftswiftui

SwiftUI Swift - Type does not conform to protocol 'Equatable'


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")
        }
    }
}

I'm getting the error:

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

When I use the "fix", then this appears:

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

I don't know what to do here, please help.

I will not change anything in galleryMemes but only pass this data without editing it later, but MemeModel still needs to be codable for other tasks, just not in DataForGalleryShow, here it can be converted to hashable if it's possible when it will make it all work


Solution

  • All you need to do is make MemeModel conform to the Hashable protocol. The compiler will do the rest for you:

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

    The compiler automatically generates the necessary Hashable methods on DataForGalleryShow (and MemeModel) for you if all properties of it fulfill the Hashable protocol.

    Manual implementation of the methods is only necessary if they cannot be generated by the compiler.