简体   繁体   中英

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

            }
        }
    }
}

Change your ForEach like this:

ForEach(array) { arr in
     if arr.show {
         Text("\(arr.text)")
     }
}
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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM