0

I have a very similar problem to Picker for optional data type in SwiftUI?.

The difference is, that I'm referencing an optional in an obserable class.

My code looks like:

enum Flavor: String, CaseIterable, Identifiable {
    case chocolate
    case vanilla
    case strawberry

    var id: String { self.rawValue }
}
class cl1: ObservableObject {
    @Published var fl: Flavor?
}
struct ContentView: View {
    @State private var selectedFlavor: cl1 = cl1()
    var body: some View {

        Picker("Flavor", selection: $selectedFlavor.fl) {
            Text("Chocolate").tag(Flavor.chocolate as Flavor?)
            Text("Vanilla").tag(Flavor.vanilla as Flavor?)
            Text("Strawberry").tag(Flavor.strawberry as Flavor?)
        }

            .padding()
    }
}

Even though I followed the other answers, as soon as I use a class object it fails.

What do I need to change to make it working?

thilo
  • 181
  • 1
  • 7

1 Answers1

0

When using an ObservableObject, you should be using a @StateObject property wrapper instead of @State -- this will allow your View to watch for updates on the @Published properties of the ObservableObject

@StateObject private var selectedFlavor: cl1 = cl1()
jnpdx
  • 45,847
  • 6
  • 64
  • 94
  • Correct answer, I forgot it, – thilo Nov 10 '21 at 17:58
  • I found: [link](https://www.hackingwithswift.com/articles/224/common-swiftui-mistakes-and-how-to-fix-them) also very helpful to gain a better understanding – thilo Feb 10 '22 at 23:28