UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

Get index count of ForEach

Forums > SwiftUI

I have a project where I retrieve json data from a remote api call and in my ForEach I filter it. I need to find out how many items are in the index that has been filtered:

ForEach(manager.filter({ "\($0)".contains(search) })) { index in

  HStack {
    Text(index.name)
   }

}

I tried to use a var and increment it, but since ForEach is a view, I can't use it there. Aftr my ForEach I want to display the count of the filtered array that is returned in index.

Text("Total names retrieved: \(someNumber)")

I have been searching online and haven't found a solution. Thanks

3      

Hey there, try this out:

struct ContentView: View {
    ...

    var items: [Index/*or whatever your object name is*/] {
        manager.filter({ "\($0)".contains(search) })
    }

    var body: some View {

        ...

        ForEach(items) { index in
            HStack {
                Text(index.name)
            }
        }

        ...

        Text("Total names retrieved: \(items.count)")

        ...
    }
}

Extract the query into the top level of your view, and then you can count it easily outside of the ForEach.

3      

Thanks. I had to change it slightly to make it work.

let items = manager.names.filter({ "\($0)".contains(search)})

I put this after the var body: some View {

Now I can get the count. Thanks for pointing me in the right direction.

3      

TAKE YOUR SKILLS TO THE NEXT LEVEL If you like Hacking with Swift, you'll love Hacking with Swift+ – it's my premium service where you can learn advanced Swift and SwiftUI, functional programming, algorithms, and more. Plus it comes with stacks of benefits, including monthly live streams, downloadable projects, a 20% discount on all books, and free gifts!

Find out more

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

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

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.