Skip to content

Instantly share code, notes, and snippets.

@pescode
Created April 7, 2020 02:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pescode/f59a5977eb140b1bdcca2d18f31aa0f9 to your computer and use it in GitHub Desktop.
Save pescode/f59a5977eb140b1bdcca2d18f31aa0f9 to your computer and use it in GitHub Desktop.
Getting the index number of an item in an Array of Identifiables
import SwiftUI
struct IdentifiableListView: View {
@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")
]
var body: some View {
List {
ForEach(Array(userList.enumerated()), id: \.1.id) { (index, item) in
HStack {
VStack {
Text(item.name)
Text(item.lastName)
}
.frame(maxWidth:.infinity)
.frame(alignment:.center)
Spacer()
}
.padding()
.background(index%2==0 ? Color.yellow:Color.orange)
}
.onDelete{ index in
self.userList.remove(at: index.first!)
}
}
}
}
struct IdentifiableListView_Previews: PreviewProvider {
static var previews: some View {
IdentifiableListView()
}
}
struct Users: Identifiable{
var id = UUID()
var name: String
var lastName: String
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment