I'm working on a workout app which has an array within an array and takes user input to populate each array.
In the first array, I can add an item to plans
using the addPlan
function. However, I cannot seem to figure out how to add items to the next level in the addExercise
function.
final class ViewModel: ObservableObject {
@Published var plans: [Plan] = []
func addPlan(_ item: String) {
let plan = Plan(name: item, exercise: [])
plans.insert(plan, at: 0)
}
func addExercise() {
}
}
Essentially, Plan
holds an array of Exercise
. Here is the model for Plan
struct Plan: Identifiable {
let id = UUID()
let name: String
var exercise: [Exercise]
static let samplePlans = Plan(name: "Chest", exercise: [Exercise(name: "Bench"), Exercise(name: "Incline Bench")])
}
These two functions should behave the same but just appending the items into different arrays.
The end result would be:
Plan 1: [Exercise1, Exercise2, Exercise3]
Plan 2: [Exercise4, Exercise5, Exercise6] etc.
Project files: LINK
What JaiRajput said, plus.
When you add an exercise, you give it a name.
So code should be:
final class ViewModel: ObservableObject {
@Published var plans: [Plan] = []
func addPlan(_ item: String) {
let plan = Plan(name: item, exercise: [])
plans.insert(plan, at: 0)
}
func addExercise(to planIndex: Int, exoName: String) {
if exoName == "" { return }
if planIndex < 0 || planIndex >= plans.count { return }
// Also test exoName does not exist there already
for exo in plans[planIndex].exercises {
if exo.name == exoName { return }
}
// All ok, add to exercises. append will add as last exercise, insert(at: 0) would append as first.
plans[planIndex].exercises.append(Exercise(name: exoName))
}
}