Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does not conform to protocol hashable?

Tags:

ios

swift

swiftui

I am trying to create view model according to JSON response but getting bellow error.

enter image description here

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?
}

trying to use result in foreach

enter image description here

Thank you for help. Please let me know if more details are required.

like image 728
Rahul Avatar asked Sep 06 '25 23:09

Rahul


1 Answers

Remove the import SwiftUI try not to use it in your ViewModels, unless really necessary. Also remove Hashable from your class declaration and outside of it create an extension like this for example:

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

Also remember that structs exists, they are great for defining your models.

One more thing, maybe instead of having an optional boolean, why not initialize it with false and in your view or viewmodel, wherever you call it first, set it to true if that's the case.

like image 180
Arturo Avatar answered Sep 09 '25 03:09

Arturo