Search code examples
swiftuiobservableoption-typepicker

Picker for optional data type in observable class in SwiftUI?


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?


Solution

  • 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()