Home > Mobile >  Value of type 'name' has no dynamic member 'name' using key path from root type
Value of type 'name' has no dynamic member 'name' using key path from root type

Time:06-09

I am learning MVVM and applying it to a simple converter app. The problem arises when I try to pass the array into a picker with ForEach. Here is my code:

Model:

struct UserOptions {
    var userOption = 0.0
    var userChoseInput = "Meters"
    var userChoseOutput = "Feets"
    var userUnits = ["Meters", "Kilometers", "Feets", "Yards"]
}

ViewModel:

class ViewModel: ObservableObject {
@Published var options = UserOptions()
var finalResult: Double {...calculations here...}
}

View:

struct ContentView: View {

@StateObject private var viewModel = RulerViewModel()

var body: some View {
    Form {
        Section {
            Picker("What is your input?", selection: $viewModel.userChoseInput) {
                ForEach($viewModel.userUnits, id: \.self) { _ in //Value of type 'ObservedObject<ViewModel>.Wrapper' has no dynamic member 'userUnits' using key path from root type 'ViewModel'
                    Text($viewModel.userChoseOutput)  
                }
            }
            .pickerStyle(.segmented)
        } header: {
            Text("Choose your input")
        }
        .textCase(nil)
        
        
        Section {
            TextField("Your number", value: $viewModel.userOption, format: .number)
                .keyboardType(.decimalPad)
                .focused($userValueIsFocused)
        }
        Section {
            Picker("What is your output?", selection: $viewModel.userChoseOutput) {
                ForEach($viewModel.userUnits, id: \.self) { _ in
                    Text(viewModel.userChoseOutput)  //Value of type 'ObservedObject<ViewModel>.Wrapper' has no dynamic member 'userUnits' using key path from root type 'ViewModel'
                }
            }
            .pickerStyle(.segmented)
        } 
        

CodePudding user response:

Use

$viewModel.options.userUnits

And

viewModel.options.userChoseOutput

As for your loop something like this would let you access the unique values

ForEach(viewModel.options.userUnits, id: \.self) { unit in
    Text(unit)
}

I suggest you also look into Measurement it will save you a lot of time when working with conversions.

  • Related