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      

Hacking with Swift is sponsored by Superwall

SPONSORED Superwall lets you build & test paywalls without shipping updates. Run experiments, offer sales, segment users, update locked features and more at the click of button. Best part? It's FREE for up to 250 conversions / mo and the Superwall team builds out 100% custom paywalls – free of charge.

Learn 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.