2

I'm trying desperately with ForEach to only display what has the value true. No matter what I try, false is also displayed. The air is out now and I think it's so simple that I just don't see it. Here is a piece of code to which it should apply:

import SwiftUI

struct txt: Identifiable {
    var id: Int
    var text: String
    var show: Bool
}

struct ContentView: View {

    @State private var array = [
        txt(id: 000, text: "True", show: true),
        txt(id: 001, text: "True", show: true),
        txt(id: 002, text: "True", show: true),
        txt(id: 003, text: "False", show: false),
        ]

    var body: some View {
        NavigationView {
            List {
                ForEach(array.indices, id: \.self) { idx in
                   Text("\(self.array[idx].text)")
                }

            }
        }
    }
}
dankell
  • 61
  • 1
  • 6

2 Answers2

4
List(array.filter { $0.show }){ (item) in
    Text(item.text)
}

UPDATE:

let ids = [0,2]
let filteredItems = array.filter { ids.contains($0.id)}

gives you filtered collection with two items only where Element.id == 0 or Element.id == 2

array.filter { $0.show } is collection of three items, where Element.show == true

you can use it as source of data

List(array.filter { ids.contains($0.id) }){ (item) in
    Text(item.text)
}

and it will produce one Text for each of its source collection

both conditions (or more) could be applied with any logical operators, as you want

user3441734
  • 16,722
  • 2
  • 40
  • 59
  • Thank you. Is there a possibility in the solution to additionally limit the ForEach? For example, just output id: 000 and id: 001, omit 002 completely and then 003 again? – dankell Feb 09 '20 at 19:14
  • Quasi limit the range additionally. The filtering however leave as it is. – dankell Feb 09 '20 at 19:18
3

Change your ForEach like this:

ForEach(array) { arr in
     if arr.show {
         Text("\(arr.text)")
     }
}
Mac3n
  • 4,189
  • 3
  • 16
  • 29