我想知道我们是否可以在ForEach中进行计数或一些数学运算,这是我的代码,我想在完成ForEach循环后获得A和B的计数。有可能吗?
struct ContentView: View {
@State var appData: [String] = ["A", "B", "A", "A", "B"]
var body: some View {
ForEach(appData, id: \.self) { item in
Text(item)
.font(.title)
.bold()
.foregroundColor(item == "A" ? Color.red : Color.blue)
}
Text("Count of A: ")
Text("Count of B: ")
}
}
答案 0 :(得分:0)
struct ContentView: View {
@State var appData: [String] = ["A", "B", "A", "A", "B"]
var body: some View {
ForEach(appData, id: \.self) { item in
let Calculation = 1 + 2
return Text(item)
.font(.title)
.bold()
.foregroundColor(item == "A" ? Color.red : Color.blue)
}
Text("Count of A: ")
Text("Count of B: ")
}
}
答案 1 :(得分:0)
您可以在主体外部声明两个计算的属性:
var aCount: Int {
appData
.filter { $0 == "A" }
.count
}
var bCount: Int {
appData
.filter { $0 == "B" }
.count
}
然后。像这样在内部使用它们:
Text("Count of A: \(aCount)")
Text("Count of B: \(bCount)")