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 Join a FREE crash course for mid/senior iOS devs who want to achieve an expert level of technical and practical skills – it’s the fast track to being a complete senior developer! Hurry up because it'll be available only until February 9th.

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.