Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SwiftUI: ForEach filters boolean

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)")
                }

            }
        }
    }
}
like image 728
dankell Avatar asked Oct 19 '25 01:10

dankell


1 Answers

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

like image 63
user3441734 Avatar answered Oct 22 '25 06:10

user3441734



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!