1)我想显示来自多个数组的数据(数据是相同的,只是分成不同的数组)。我该怎么做?
2) 我只想显示数组中的特定选择。
我在这些数组中创建了一种名为“groupid: Int”的 ID 形式,它出现在数组中。在这种情况下,我想从多个数组中提取所有带有“groupid: 1”的条目并将它们显示在列表中。
//我想在其中显示最终列表的 View :
import SwiftUI
struct French1View : View {
var body: some View {
NavigationView {
List {
ForEach(XXXXX????) { grape in
GrapeCell(grape: grape)
}
.navigationBarTitle("French wine grapes")
}
}
}
}
//数组:
let BGrapes = [
Grape(id: 1,
groupid: 1,
name: "Barbera",
type: "White"),
Grape(id: 2,
groupid: 2,
name: "Bosco",
type: "Red")
]
let CGrapes = [
Grape(id: 1,
groupid: 1,
name: "Barbera",
type: "White")
]
正如您在代码中看到的那样,我被困在我应该输入的地方(对于这个例子)写成“XXXXX????”
我试过写“(BGrapes, CGrapes) && grape.groupid(1)”但没有成功。
最佳答案
欢迎来到 SO。 :)
您可以将 Grape 数组与 +
(Swift 5+)和 groupID
的 filter
连接起来:
var body: some View {
NavigationView {
List {
ForEach((bGrapes + cGrapes).filter { $0.groupID == 1 }, id: \.self) { grape in
GrapeCell(grape: grape)
}
.navigationBarTitle("French wine grapes")
}
}
}
产生:
如果您希望结果UNIQUE:
var body: some View {
NavigationView {
List {
ForEach(uniqueGrapesFirstGroup(), id: \.self) { grape in
GrapeCell(grape: grape)
}
.navigationBarTitle("French wine grapes")
}
}
}
func uniqueGrapesFirstGroup() -> [Grape] {
let allGrapes = (bGrapes + cGrapes)
let allGrapesFirstGroup = allGrapes.filter { $0.groupID == 1 }
let allUniqueGrapesFirstGroup = Set(allGrapesFirstGroup)
return Array(allUniqueGrapesFirstGroup)
}
产生:
完整代码:
struct Grape: Hashable {
let id: Int
let groupID: Int
let name: String
let type: String
}
struct GrapeCell: View {
let grape: Grape
var body: some View {
Group {
Text("Name: \(grape.name)")
}
}
}
struct FrenchView: View {
let bGrapes = [
Grape(id: 1,
groupID: 1,
name: "Barbera",
type: "White"),
Grape(id: 2,
groupID: 2,
name: "Bosco",
type: "Red")
]
let cGrapes = [
Grape(id: 1,
groupID: 1,
name: "Barbera",
type: "White")
]
var body: some View {
NavigationView {
List {
ForEach(uniqueGrapesFirstGroup(), id: \.self) { grape in
GrapeCell(grape: grape)
}
.navigationBarTitle("French wine grapes")
}
}
}
func uniqueGrapesFirstGroup() -> [Grape] {
let allGrapes = (bGrapes + cGrapes)
let allGrapesFirstGroup = allGrapes.filter { $0.groupID == 1 }
let allUniqueGrapesFirstGroup = Set(allGrapesFirstGroup)
return Array(allUniqueGrapesFirstGroup)
}
}
关于arrays - 使用唯一的 Int 在 SwiftUI 中仅显示数组的选择,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57291294/