Lately I've been learning SwiftUI, which is pretty neat. I've noticed that when it comes to displaying a list of items: you often want access to the index value as part of your ForEach or List in order to reference a @Binding of the larger collection.

Forums like Stackoverflow are littered with questions around this issue: how to cleanly iterate over an Array to use its elements in subviews while maintaining a Binding so any addition or removal from the collection is reflected in the UI. There's essentially two types of answers:

Both of these are kind of ugly and cumbersome. I come from a background of loving and using Ruby, where this problem is solved with .each_with_index, passing both an index and the value into the included closure.

EnumForEach (and EnumList)

As an exercise to learn about Generics and Closures in Swift, I decided to create a function similar to .each_with_index to complement ForEach and List. If we had this rather cumbersome code using .enumerated():

ForEach(Array(array.enumerated()), id: \.element) { index, element in
    ...
}

With my library function, this can become:

EnumForEach(array) { index, element in
    ...
}

Note that in both of these examples, your elements must implement the protocol Identifiable. The same transformation can be done with List, by swapping for EnumList.

You can see the code for these functions here. I hope others find them useful. If you have other/better ways of achieving this, please let me know!

What do you think? I'd love to hear from you. Here is a link to the source for this article on github. Please open an issue, send me a pull-request, or just email me at jubi@jubishop.com