2

I am creating a little workout app using SwiftUI. I have a list of exercises stored in Core Data, and when the user selects one from the list I am adding it to an array in the state.

@State private var workoutExercises: [CDWorkoutExercise] = []

...

func onSelectExercise(exercise: CDExercise) {
    let newWorkoutExercise = CDWorkoutExercise(context: self.moc)
    newWorkoutExercise.exercise = exercise
    newWorkoutExercise.reps = 8
    newWorkoutExercise.sets = 3

    workoutExercises.append(newWorkoutExercise)
}

I have a ForEach that loops over the exercise core data objects that have been added to the array and display the exercise they added as well as allow the user to use an input, preferably a Stepper or Textfield, to change the number of reps to perform for the exercise.

ForEach(workoutExercises, id: \.self) { workoutExercise in
    VStack {
        Text(workoutExercise.exercise?.wrappedName ?? "Unknown")

        Stepper("Reps", value: $workoutExercise.reps, in: 1...100)
    }
}

However, when I try to bind the object to the input Xcode displays the error Use of unresolved identifier: $workoutExercise (in this case on the line where the Stepper is defined) and I'm unsure how to resolve the issue or where I've gone wrong.

1
  • As long as your model object can't be represented as a stateful object, you can't access it's projectedValue. That effectively means, the CDWorkoutExercise type must be represented as an object which can be observed of its change over time. Commented Dec 17, 2019 at 3:05

1 Answer 1

3

If I correctly understood your intention and your model the following should work

TextField("", text: Binding<String>(
    get: {workoutExercise.exercise?.wrappedName ?? "Unknown"}, 
    set: {workoutExercise.exercise?.wrappedName = $0}))
Sign up to request clarification or add additional context in comments.

1 Comment

Sorry if I wasn't clear, I'm having issues binding the Int16 value reps to the Stepper or a TextField. If it would be helpful, I can share my NSManagedObject code for the core data model (I have code gen set to manual/none).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.