WWDC22 SALE: Save 50% on all my Swift books and bundles! >>

Filter ForEach From a Binding

Forums > Swift

I have follow this tutorial, but I can't filter array anymore if I use binding.

https://www.hackingwithswift.com/quick-start/swiftui/how-to-create-a-list-or-a-foreach-from-a-binding

Im getting an error

Generic struct 'ForEach' requires that 'Binding<[Contact]>.Element' (aka 'Binding<Contact>') conform to 'Hashable'

If I remove $ binding, Im able to do filtering again.

This is my class

class ContactsViewModel: ObservableObject {

    @Published var contactsList: [Contact] = []
    @Published var favoritesList: [Contact] = []
 }

1      

Here's a short bit I wrote in another forum post about ForEach: Notes on ForEach

TLdr: ForEach is a view factory. It makes a number of views from a collection of things.

If you have a collection of book objects, ForEach will loop through each book object in your collection and make a BookView for each of those individual objects.

The error message gives you a clue:

Generic struct 'ForEach' requires that 'Binding<[Contact]>.Element' (aka 'Binding<Contact>') conform to 'Hashable'

What is the Contact object you're asking ForEach to process? You do not show this object in your code snip. XCode is complaining that you're not providing a collection of Contact objects. If you are, your Contact objects are not Hashable.

@rooster wrote a nice piece on Identifiable and Hashable. Read it here: All about Hashable

1      

Hacking with Swift is sponsored by Emerge

SPONSORED Optimize your app’s startup time, binary size, and overall performance using Emerge’s advanced app optimization and monitoring tools. Reliably measure app size, speed up your app's startup time with Emerge's Launch Booster, and much more. Emerge is actively used by many of the top mobile development teams in the world.

Find out more

Sponsor Hacking with Swift and reach the world's largest Swift community!

Reply to this topic…

You need to create an account or log in to reply.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.