0

I have down code which makes some Text in a ForEach loop, this loop use (id: .self) which is Int, but in this case our generated ( id = UUID() ) would ignored! And ForEach would work with some internal Int numbers! How we can force ForEach to take our built UUID as id?

    struct Data: Identifiable
{
    let id  = UUID()
    var name: String
}

let Data1 = Data(name: "Data 1")
let Data2 = Data(name: "Data 2")
let Data3 = Data(name: "Data 3")
let Data4 = Data(name: "Data 4")

class DataModel: ObservableObject
{
    @Published var items: [Data] = [Data1, Data2, Data3, Data4]
}



struct ContentView: View
{
    
    @StateObject var dataModel = DataModel()
    
    var body: some View
    {
        
        ForEach(dataModel.items.indices, id: \.self) { index in // ← Here: I want UUID 
            
            Text(dataModel.items[index].name)
                .font(.title2)
                .padding()
            
            
        }
    }
}
ios coder
  • 1
  • 4
  • 31
  • 91
  • 1
    You can do this: `ForEach(dataModel.items) { item in ... }` because each item conforms to `Identifiable`. Also, unrelated, but I'd suggest not naming it `Data`, since there's already this type defined in Foundation – New Dev Nov 02 '20 at 03:21
  • about naming you have right, this codes are just simple sample! BUT about "ForEach(dataModel.items) { item in ... }" I know it, but I can not use that way because I need to read index in my real codes – ios coder Nov 02 '20 at 03:27

2 Answers2

1

You can use zip as mentioned in How do you use .enumerated() with ForEach in SwiftUI?

ForEach(Array(zip(dataModel.items.indices, dataModel.items)), id: \.1) { index, item in
  // index and item are both safe to use here
}
Joe
  • 3,664
  • 25
  • 27
  • thanks, I looked to the link, it was a little high-level for me, I did not understand why \.1 ? – ios coder Nov 02 '20 at 04:44
  • `zip` returns a sequence of tuple pairs. You can access the second element in a tuple pair with `.1` which in this case is the item (`Data`). You can look for information about Swift tuples to find out more about the syntax. – Joe Nov 02 '20 at 05:58
-1

you could try this:

ForEach(dataModel.items.map{ $0.id }, id: \.self) { uuid in // ← Here: I want UUID