Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

LoadingState<Movie> conform to Equatable

I have my LoadingState defined as follows:

enum LoadingState<T: Codable> {
    case none
    case loading
    case success(T)
    case error(Error)
}

Movie is defined below:

struct Movie: Codable {
    let title: String
}

In my SwiftUI view I am trying to use the task(id) modifier as shown below:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

struct ContentView: View {
    
    @State private var loadingState: LoadingState<Movie> = .none
    
    var body: some View {
        VStack {
            Button("Perform Time Consuming Operation") {
                loadingState = .loading
            }.buttonStyle(.borderedProminent)
        }.task(id: loadingState) {
            
        }
    }
}

But I get the following error:

Instance method 'task(id:priority:_:)' requires that 'LoadingState<Movie>' conform to 'Equatable'

Any ideas?

>Solution :

You have to make your types conform to Equatable. Exactly what the error message says.

For your Movie type it can be autogenerated, you just have to add Equatable protocol name to the declaration:

struct Movie: Codable, Equatable { // <- here
    let title: String
}

For the enum it’s a bit tricker, if you want it to work only with T also being Equatable you may declare it as

enum LoadingState<T: Codable & Equatable>: Equatable {
    // case … case … etc
}

// or
enum LoadingState<T>: Equatable where T: Codable, T: Equatable {
    // case … case … etc
}

Or, if you want LoadingState work with any T, but to conform to Equatable iff T is also Equatable you have to do it in extension (your original enum declaration stays):

extension LoadingState: Equatable where T: Equatable { }

You may also need to do something with .error(Error) case too, it may want to declare it as generic type and attach Equatable to it too, as we did with T above.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading