0

I'm working on an array of filters which are connected to a database. The filters (categories in this case) are successfully rendered. However, there are many duplicates. I'm new to SwiftUI and I'm eager to know if there's any smart way to remove duplicates in my foreach.

Hope someone can help me! Thanks in advance!

Find the code below:

{
  HStack(spacing: 8){
    ForEach(artikel.content) { filter in
        FilterButton2_0(selected: self.$selected, name: filter.categorie ?? "", selectedFilter: self.$selectedFilter)
                     }
                  }.padding(.leading, 20)
              }
  • It’s probably better to remove them before you use the array in your view, like changing the database query or when receiving the results from the query – Joakim Danielson Apr 03 '21 at 07:42
  • or put your content inside a Set to get only one occurrence of each elements – lorenzo Apr 03 '21 at 08:05
  • How would you do that in SwiftUI? I saw many Swift examples, but couldn't find any SwiftUI ones.. – Joël van Bodegraven Apr 03 '21 at 08:14
  • @JoakimDanielson That was the idea initially, but there are some limitations. So that is not possible ;( – Joël van Bodegraven Apr 03 '21 at 08:15
  • As @lorenzo proposed, I believe you could just place filter array in Set like this, Set(filter), but your filters class should conform to Hashable protocol. – Ivan Barabanshchykov Apr 03 '21 at 08:57
  • You could add a computed property in an extension to the `artikel` type that returns only unique content using Set perhaps. – Joakim Danielson Apr 03 '21 at 09:38
  • You can use the last extension from [this answer](https://stackoverflow.com/a/25739498/15494229). It's using Set, you need you struct conform to Hashable. And now, code will be `ForEach(artikel.content.uniqued())` – Higherous Apr 03 '21 at 09:23
  • A disadvantaged of this solution is that uniqued() will be called everytime this part of the UI is redrawn even if the content array hasn't changed. – Joakim Danielson Apr 03 '21 at 09:40
  • As a solution, when receiving data from the network, get an already existing array, add new values and remove duplicates and all the values that are in the previous array. – Higherous Apr 03 '21 at 09:48

0 Answers0