SwiftUI: ForEach filters boolean

て烟熏妆下的殇ゞ 提交于 2021-01-28 09:34:05

问题


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

            }
        }
    }
}

回答1:


Change your ForEach like this:

ForEach(array) { arr in
     if arr.show {
         Text("\(arr.text)")
     }
}



回答2:


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



来源:https://stackoverflow.com/questions/60138431/swiftui-foreach-filters-boolean

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!