My question is similar to this one -> How to use Bind an Associative Swift enum?
I have modified the example provided to be an array.
The GroupView
accepts a binding as a parameter because I want the GroupView to modify the data in the enum. The difference between the original question and this one is that in this one, the enums are an array instead of a single one.
How to i extract a binding from the enums so that the GroupView
can modify the enums correctly?
Here is the modified code
import SwiftUI
struct ContentView: View {
@ObservedObject var viewModel = ViewModel()
var body: some View {
VStack {
ForEach(0..<viewModel.box.instructions.count) { index -> GroupView in
let instruction = self.viewModel.box.instructions[index]
return GroupView(v: ????) // How do i extract the binding here???
}
}
}
}
struct GroupView: View {
@Binding var v: Group
var body: some View {
Button("Hello: \(self.v.groupValue)") {
self.v.groupValue += 1
}
}
}
class ViewModel : ObservableObject {
@Published var box: Box!
init() {
box = Box(instructions: [
Instruction.group(Group(groupValue: 10)),
Instruction.group(Group(groupValue: 20))
])
}
}
struct Group { var groupValue: Int }
enum Instruction { case group(Group) }
struct Box { var instructions: [Instruction] }
Ok, if the array is fixed in size:
If your array is not fixed, you should consider this from iOS13 release notes:
Then, if your array is not fixed in size, you may need more code:
As I mentioned in the comments. You cannot make an enum identifiable (if you can, please do tell how!). So the only alternative is to use
id: \.self
in theForEach
. But to do that, we need to makeInstruction
conform toHashable
.Also, to get the binding, we need the index of its position. The solution here (findIndex), may not be the best thing performance wise, but I don't expect your Instructions array to have thousands of elements... so that should be ok.