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 try! Swift Tokyo.

SPONSORED Ready to dive into the world of Swift? try! Swift Tokyo is the premier iOS developer conference will be happened in April 9th-11th, where you can learn from industry experts, connect with fellow developers, and explore the latest in Swift and iOS development. Don’t miss out on this opportunity to level up your skills and be part of the Swift community!

Get your ticket here

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.