Skip to content

Instantly share code, notes, and snippets.

@alenm
Created February 14, 2021 23:17
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 alenm/5a88833d6f6e5638165d9f8284133cb8 to your computer and use it in GitHub Desktop.
Save alenm/5a88833d6f6e5638165d9f8284133cb8 to your computer and use it in GitHub Desktop.
ForEach over an Array of Tuples. Note in order for this to work properly you need to have some unique id. In this example that is in the Integer. If it's not unique you will run into issues
// Example A
// This example it works fine because `id:\.0` is an Int and is unique
struct Example: View {
var tupleListExample: [(Int, String)] = [
(1, "A"),
(2, "B"),
(3, "C"),
]
var body: some View {
VStack {
ForEach(tupleListExample, id:\.0) { item in
HStack {
Text("\(item.0)")
Spacer()
Text(item.1)
}
}
}
}
}
// Example B - You will have problems
// This example will not work as well because `id:\.0` is a Date() and in this example all 3 dates could be the same
// In this example I'm generating the `tupleListExample` and it does it so fast it could be that all 3 Date() are exactly the same
struct Example: View {
var tupleListExample: [(Date, String)] = [
(Date(), "A"),
(Date(), "B"),
(Date(), "C"),
]
var body: some View {
VStack {
ForEach(tupleListExample, id:\.0) { item in
HStack {
Text("\(item.0)")
Spacer()
Text(item.1)
}
}
}
}
}
// The lesson to learn here is with `ForEach` would like an id that is unique, this is why it looks for a property that is `Hashable`
// if you find yourself in situation where you are iterating over an array of tuple try to see if you have a unique property within the tuple
// OR maybe consider converting your tuple into a struct and make an id that is `Identifiable`.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment