In ContentView: View
I have an array of days with some data attached to it from HealthKit. The day is unique. The array is printing fine and everything to do that with that is correctly populated.
//Prep workouts to display
public struct workoutHistory {
var workoutDate: Date
var strengthCount: Int
var cardioCount: Int
var flexibilityCount: Int
}
@State public var workoutHistoryByDay: [workoutHistory] = []
Then in the body I try to display every date in a list (just to test at the moment)
ForEach(workoutHistoryByDay) { workoutDay in
Text("\(workoutDay.workoutDate)")
Text("\(workoutDay.strengthCount)")
}
When I do this I get the error:
Referencing initializer 'init(_:content:)' on 'ForEach' requires that 'ContentView.workoutHistory' conform to 'Identifiable'
I have tried updating my struct to include : Identifiable
and I get the error
Type 'ContentView.workoutHistory' does not conform to protocol 'Identifiable'
I have also tried updating the ForEach to include ID
ForEach(workoutHistoryByDay, id: .workoutDate) { workoutDay in
Text("\(workoutDay.workoutDate)")
Text("\(workoutDay.strengthCount)")
}
And I get the error
Generic parameter 'ID' could not be inferred
My question is, how to I properly list every .workoutDate
and .strengthCount
in my array workoutHistoryByDay
? Thank you.
CodePudding user response:
You have to inherit Identifiable
protocol to your struct model and need to confirm ID.
public struct workoutHistory: Identifiable { //<== here
public var id: Date { //<== here
self.workoutDate
}
var workoutDate: Date
var strengthCount: Int
var cardioCount: Int
var flexibilityCount: Int
}
you can return workoutDate
as an id if the date is unique else you have to set a unique id.
CodePudding user response:
try this approach, as in this sample code, works very well for me:
struct ContentView: View {
// -- here some test workout
@State public var workoutHistory: [Workout] = [
Workout(workoutDate: Date(), strengthCount: 1, cardioCount: 2, flexibilityCount: 3),
Workout(workoutDate: Date(timeIntervalSinceNow: Double(86400 * 1)), strengthCount: 2, cardioCount: 2, flexibilityCount: 3),
Workout(workoutDate: Date(timeIntervalSinceNow: Double(86400 * 2)), strengthCount: 3, cardioCount: 2, flexibilityCount: 3)]
var body: some View {
List {
ForEach(workoutHistory) { workout in
Text("\(workout.workoutDate)")
Text("\(workout.strengthCount)")
}
}
}
}
public struct Workout: Identifiable { // <-- here
public let id = UUID() // <-- here
var workoutDate: Date
var strengthCount: Int
var cardioCount: Int
var flexibilityCount: Int
}
You would gain a lot by doing the tutorial again at: https://developer.apple.com/tutorials/swiftui/