Search code examples
swiftswiftuipicker

How to assign a value selected from a Picker to a variable in another class?


I would like to use a picker to select a value and store that value in a variable contained in another class. How can I do that? Here is my code:

my contentview

struct ContentView: View {
    
    @State public var selectedOperator = ""
    @ObservedObject var bitwiseCalculator = BitwiseCalculator()
    
    let operators = ["AND", "OR", "XOR"]
    
    var body: some View {
            VStack {
                Picker("Operator", selection: $selectedOperator) {
                    ForEach(operators, id: \.self) { op in
                        Text(op)
                    }
                }
            }
    }
}

and the variable in the class where I want to save it

class BitwiseCalculator: ObservableObject {
    
    @Published var bitwiseOperator = ""
    
}

Solution

  • Use

    $bitwiseCalculator.bitwiseOperator 
    

    & switch your

    @ObservedObject to @StateObject