Just a coder
Just a coder

Reputation: 16730

How to update view when value inside Enum changes with SwiftUI?

Here is my code. Run the MainView struct, and click on the button which should update the word first to the word hello. It does not update at all even though the logs show that the data is correctly updated. Therefore is there no way to get the view to update when a value changes inside an enum?

The only way I got it to work was a nasty hack. To try the hack just uncomment the 3 lines of commented code and try it. Is there a better way?

I looked at this similar question, but the same problem is there -> SwiftUI two-way binding to value inside ObservableObject inside enum case

struct MainView: View {
    @State var selectedEnum = AnEnum.anOption(AnObservedObject(string: "first"))
    // @State var update = false
    var body: some View {
        switch selectedEnum {
        case .anOption(var value):
            VStack {
                switch selectedEnum {
                case .anOption(let val):
                    Text(val.string)
                }
                TestView(object: Binding(get: { value }, set: { value = $0 }),
                         callbackToVerifyChange: callback)
            }
            // .id(update)
        }
    }
    
    func callback() {
        switch selectedEnum {
        case .anOption(let value):
            print("Callback function shows --> \(value.string)")
            // update.toggle()
        }
    }
}

class AnObservedObject: ObservableObject {
    @Published var string: String
    init(string: String) {
        self.string = string
    }
}

enum AnEnum {
    case anOption(AnObservedObject)
}

struct TestView: View {
    @Binding var object: AnObservedObject
    let callbackToVerifyChange: ()->Void
    var body: some View {
        Text("Tap here to change the word 'first' to 'hello'")
            .border(Color.black).padding()
            .onTapGesture {
                print("String before tapping --> \(object.string)")
                object.string = "hello"
                print("String after tapping --> \(object.string)")
                callbackToVerifyChange()
            }
    }
}

Upvotes: 1

Views: 1516

Answers (1)

Lucas
Lucas

Reputation: 6729

You need to declare your enum Equatable.

Upvotes: 0

Related Questions