如何在SwiftUI的索引模式下使用我自己的customID作为ForEach的id?
我制作了一个CustomStruct,它制作了自己的customID,我可以在item模式下使用这个customID作为ForEach的id,然后我尝试在index模式下使用我自己的customID作为ForEach的id,但是它给出了错误,它说Int没有customID的成员,这就是我制作customID的全部原因,就是为了不使用Int作为id,但是使用我自己的customID。我怎样才能解决这个问题如何在SwiftUI的索引模式下使用我自己的customID作为ForEach的id?,swiftui,Swiftui,我制作了一个CustomStruct,它制作了自己的customID,我可以在item模式下使用这个customID作为ForEach的id,然后我尝试在index模式下使用我自己的customID作为ForEach的id,但是它给出了错误,它说Int没有customID的成员,这就是我制作customID的全部原因,就是为了不使用Int作为id,但是使用我自己的customID。我怎样才能解决这个问题 struct ContentView: View { @State
struct ContentView: View {
@State var arrayOfCustomStruct: [CustomStruct] = [CustomStruct]()
var body: some View {
Spacer()
// VStack {
//
// ForEach (arrayOfCustomStruct, id: \.customID) { item in
//
// Text( String(item.customID) )
//
// }
//
// }
VStack {
ForEach (arrayOfCustomStruct.indices, id:\.self) { index in // << here I want this happen: -----> id: \.customID
Text( String(arrayOfCustomStruct[index].customID) )
}
}
Spacer()
HStack {
Spacer()
Button("add new item") {
arrayOfCustomStruct.append( CustomStruct(name: "New Item") )
}
Spacer()
Button("remove an item") {
if arrayOfCustomStruct.count > 0 {
arrayOfCustomStruct.remove(at: arrayOfCustomStruct.count-1 )
}
}
Spacer()
}.padding()
}
}
struct CustomStruct {
init(name: String) {
CustomStruct.indexOfId += 1
self.name = name
}
private static var indexOfId: UInt64 = 0
let customID: UInt64 = CustomStruct.indexOfId
var name: String
}
如果您想按项同时拥有索引和id,可以使用枚举,如
ForEach (Array(arrayOfCustomStruct.enumerated()), id:\.1.customID) { index, item in
Text( String(arrayOfCustomStruct[index].customID) )
}
如果您想按项同时拥有索引和id,可以使用枚举,如
ForEach (Array(arrayOfCustomStruct.enumerated()), id:\.1.customID) { index, item in
Text( String(arrayOfCustomStruct[index].customID) )
}
你读过我的书名吗?海关!UUID不是自定义的。你读过我的标题吗?海关!UUID不是自定义的。它正在工作,但我怎么能只使用索引呢?这是我的想法,让我知道我是对还是错?当我们只是使用ForEach的item模式时,id会去找到我们的customID,然后它会自动同步到它!但当我们使用justindex模式时,ForEach不会访问我们的customID,因为它只关心范围!由于Range是一种Int类型,它会尝试在Int中查找customID来同步自身!但是它找不到它!因为customID是CustomStruct的属性,而不是Int。到目前为止这是正确的吗?知道了这一点,struct不能相互继承,那么就没有办法使用ForEach的索引模式和customID,对吗?嗯。。。可能您已经被术语“mode”卡住了——这里没有任何“mode”,ForEach只是使用集合进行迭代,并使用id作为集合中元素的属性。因此,当您使用
arrayOfCustomStruct.index
时,您不会在索引模式下迭代arrayOfCustomStruct,您只需在整数范围内迭代,因此id只能用于整数。(当然,您可以使用可计算属性向整数添加扩展,并将其用作id,但这不会改变意义)@Asperi:U刚才用正确的语法说了我说的话,我也用了你关于扩展的建议!现在Int可以访问customID了。检查我的更新,它也在索引模式下工作。它正在工作,但我怎么能只用索引呢?这是我的想法,让我知道我是对还是错?当我们只是使用ForEach的item模式时,id会去找到我们的customID,然后它会自动同步到它!但当我们使用justindex模式时,ForEach不会访问我们的customID,因为它只关心范围!由于Range是一种Int类型,它会尝试在Int中查找customID来同步自身!但是它找不到它!因为customID是CustomStruct的属性,而不是Int。到目前为止这是正确的吗?知道了这一点,struct不能相互继承,那么就没有办法使用ForEach的索引模式和customID,对吗?嗯。。。可能您已经被术语“mode”卡住了——这里没有任何“mode”,ForEach只是使用集合进行迭代,并使用id作为集合中元素的属性。因此,当您使用arrayOfCustomStruct.index
时,您不会在索引模式下迭代arrayOfCustomStruct,您只需在整数范围内迭代,因此id只能用于整数。(当然,您可以使用可计算属性向整数添加扩展,并将其用作id,但这不会改变意义)@Asperi:U刚才用正确的语法说了我说的话,我也用了你关于扩展的建议!现在Int可以访问customID了。检查我的更新,它也在索引模式下工作。