Reputation: 1
I made a CustomStruct which it makes own customID, I could use this customID as id for ForEach in item mode, then I tried to use my own customID as id for ForEach in indices mode, but it gives error, It says Int has no member of customID, which my all reason of making customID was and is to not using Int as id, but using my own customID. How could I solve this issue?
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
}
Update: customID in Int has completely deferent personality than customID in CustomStruct! It is NOT perfect as CustomStruct.
extension Int {
private static var indexOfId: Int = -1
var customID: Int {
Int.indexOfId += 1
return Int.indexOfId
}
}
Upvotes: 1
Views: 1778
Reputation: 258413
If you want to have both indices and id by item, you can use enumerated, like
ForEach (Array(arrayOfCustomStruct.enumerated()), id:\.1.customID) { index, item in
Text( String(arrayOfCustomStruct[index].customID) )
}
Upvotes: 1