Search code examples
iosarraysxcodeswiftuiios14

Search through Array from Data Model in SwiftUI


Another tricky SwiftUI problem I cannot solve!

I have 2 lists in a view, each one is reading from a Data Model struct. When a row is selected in the first list I am updating a @State with the title of the row selected.

In my second list the data model has an array that may or may not match the title of the updated @State. I am trying to search through the array to see if it matches the newly selected @State string and only present the row if it matches, but I cannot work out how to search through each array for each row. How do I access the array to see if it matches @State?

I haven't included the 2 row views ApplicationsListRow and ProductListRow as these are simple HStacks that just source the title from the data model.

Here is my view with the 2 list:

struct ProductListTabApplications: View {
    
    @State private var selectedOption = "Food"
    
    var applications: [ApplicationModel] = applicationData
    var products: [ProductModel] = productData
    
    var body: some View {
        HStack {
            List(){
                ForEach(applications) { item in
                    Button(action: {
                        self.selectedOption = item.title
                    }) {
                        ApplicationsListRow(application: item)
                    }
                }
            }
            List{
                ForEach(products) { item in
                    NavigationLink(destination: ProductTabView(product: item)) {
                        ProductListRow(product: item)
                    }
                }
            }
        }
    }
}

I have tried having for loops and if statements in the second list but I cannot work out a way to access the the array to see if it exists. Here is one of the examples I tried:

ForEach(products) { item in
     ForEach(item) { application in
         if item.application[application] == selectedOption {
            // list items
          }
      }
 }

Simplified data model:

struct ProductModel: Identifiable {
var id = UUID()
var title: String
var application: [String]  
}

Simplified struct:

let productData: [ProductModel] = [
    ProductModel(
        title: "product1",
        application: ["Food","Metals","Beverage"]
    ),
    ProductModel(
        title: "product2",
        application: ["Beverage"]
    ),
]

Solution

  • you can use filter to find matches in your lists.

    example:

    let matchedItems = products.filter {
        product in
        let list = product.application
        for item in list {
            if item == selectedOption {
                return true
            }
        }
        return false
    }
    

    now you have all products that have a matched string in their application array.