swift nub
swift nub

Reputation: 2937

How to use Bind an Associative Swift enum?

I have a GroupView that accepts a binding as a parameter because I want the GroupView to modify the data in the enum.

Can some help me on how to accomplish this?

import SwiftUI
struct ContentView: View {
    @ObservedObject var viewModel = ViewModel()
    var body: some View {
        VStack {
            GroupView(group: /* What do i put here? */)  // <----------------
        }
    }
}

struct GroupView: View {
    @Binding var group: Group
    var body: some View {
        Text("Hello World")
    }
}

class ViewModel : ObservableObject {
    @Published var instruction: Instruction!
    init() {
        instruction = .group(Group(groupTitle: "A Group struct"))
    }
}

enum Instruction {
    case group(Group)
}
struct Group { var groupTitle: String }

Upvotes: 1

Views: 519

Answers (1)

kontiki
kontiki

Reputation: 40529

Well, this certainly will work... but probably there's a better approach to your problem. But no one is in a better position than you, to determine that. So I'll just answer your question about how to pass a binding.

struct ContentView: View {
    @ObservedObject var viewModel = ViewModel()
    var body: some View {

        VStack {
            GroupView(group: viewModel.groupBinding)
        }
    }
}

class ViewModel : ObservableObject {
    @Published var instruction: Instruction!

    init() {
        instruction = .group(Group(groupTitle: "A Group struct"))
    }

    var groupBinding: Binding<Group> {
        return Binding<Group>(get: {
            if case .group(let g) = self.instruction {
                return g
            } else {
                return Group(groupTitle: "")
            }
        }, set: {
            self.instruction = .group($0)
        })
    }
}

Upvotes: 4

Related Questions