GO FURTHER, FASTER: Try the Swift Career Accelerator today! >>

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 Essential Developer.

SPONSORED Transform your career with the iOS Lead Essentials. Unlock over 40 hours of expert training, mentorship, and community support to secure your place among the best devs. Click for early access to this limited offer and a FREE crash course.

Click to save your free spot now

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.