Does not conform to protocol hashable?

Viewed 4378

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.

2 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 lol 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.

The compiler is simply telling you that by saying

", Hashable" in your class declaration, you are promising to adhere to the rules of protocol Hashable. Additionally Hashable inherits from protocol Equatable. To adhere to the rules of Hashable you are also saying you agree to the rules of Equatable. The rules of protocols are simply a list of functions that you promise to implement and or variables you promise to have.

In your case you need this requirement for protocol equatable: enter image description here

And you need to fulfill this promise for protocol Hashable:

enter image description here

You can find this type of information by looking carefully through the documentation. https://developer.apple.com/documentation/swift/hashable

In your case you need to add two methods inside of DeclarationListViewModel

extension DeclarationListViewModel { static func ==(lhs: DeclarationListViewModel, rhs: DeclarationListViewModel) {

    return lhs.yesNo == rhs.yesNo &&
           lhs.title == rhs.title
}

}

and to be Hashable

func hash(into hasher: inout Hasher) {
    hasher.combine(yesNo)
    hasher.combine(title)
}
Related