Getting the index number of an item in an Array of Identifiable
Playing with SwiftUI I got a little challenge… I had a list of items, and I wanted to alternate the background color if the number of the cell was odd or even.
Lets say we have the following model
struct Users: Identifiable{
var id = UUID()
var name: String
var lastName: String
}And we create our list
@State var userList = [
Users(name: "Sarah", lastName: "Gates"),
Users(name: "Jack", lastName: "Black"),
Users(name: "Kate", lastName: "Anderson"),
Users(name: "Bill", lastName: "Jobs"),
Users(name: "Steve", lastName: "Gates")
]Normally, we use a List with a ForEach to draw our list
List {
ForEach(userList) { user in
HStack {
VStack {
Text(user.name)
Text(user.lastName)
}
.frame(maxWidth:.infinity)
.frame(alignment:.center)
Spacer()
}
.padding()
.background(Color.yellow)
}
}Now, we need to know if the cell of the item is even or odd to draw a different background color in each case… how can we do that?
Get Victor Corvalán’s stories in your inbox
Join Medium for free to get updates from this writer.
Probably our first attempt to accomplish this, would be the following code
List {
ForEach(userList.indices, id: \.self) { index in
HStack {
VStack {
Text(userList[index].name)
Text(userList[index].lastName)
}
.frame(maxWidth:.infinity)
.frame(alignment:.center)
Spacer()
}
.padding()
.background(index%2==0 ? Color.yellow:Color.orange)
}
}That’s ok. It works. But now let’s add the onDelete modifier to see what happens.
List{
ForEach(userList.indices, id: \.self){ index in
VStack{
Text(userList[index].name)
Text(userList[index].lastName)
}
.background(index%2==0 ? Color.yellow : Color.blue)
}
.onDelete{ index in
self.userList.remove(at: index.first!)
}You will notice that the animation is kinda ugly here. So a better way is to enumerate this collection and convert the enumeration to an array.
List{
ForEach(Array(userList.enumerated()), id: \.1.id){ (index, item) in
VStack{
Text(item.name)
Text(item.lastName)
}
.background(index%2==0 ? Color.yellow : Color.blue)
}
.onDelete{ index in
self.userList.remove(at: index.first!)
}That’s it! Hope that this help if you get stuck in something similar! I would love to read another solution if you have one!








