Evil Emperor Zurg
Evil Emperor Zurg

Reputation: 15

Filtering a For Each loop - swiftui

I'm new at SwiftUI so apologies if this is a really dumb question but I can't seem to figure out how to filter the sessions where I want to filter the data by either the section ID or the section name. Really appreciate any help!

let sessions = Bundle.main.decode([SessionsSection].self, from: "sessions.json")
    
    
var body: some View {
    
    //NavigationView {
        

        List {
            
            ForEach(sessions) { section in
                Section(header: Text(section.name)) {
                    
                    // Items in sections
                    ForEach(section.items) { item in
                        
                        ItemRow(item: item)
                    }
                }
                
            }
        } // List end bracket

Upvotes: 0

Views: 1030

Answers (2)

Pranav Kasetti
Pranav Kasetti

Reputation: 9925

You can also filter using keypaths in Swift 5:

extension SessionsSection {
  var isIncluded: Bool {
    return self.id >= 1 || self.name == "selection"
  }
}

ForEach(sessions.filter(\.isIncluded)) { section in
  // Insert code from above.
}

Upvotes: 1

davidev
davidev

Reputation: 8517

You can just use .filter(_ :) function in the ForEach

ForEach(sessions.filter {
    $0.id == 0 //<< here comes your predicate, id or name. Return true if should be included
}) { section in

Upvotes: 2

Related Questions