@Justin missed a big lesson on protocols!
The code in my preview struct appears to be correct
so I'm struggling to locate the origin of this error.
Struct is a Box
Think of your struct
as a box that holds your variables and methods for your specific purpose. This is easy to envision, you just add your vars
and funcs
to describe workouts, interesting places around town, store inventory, school students, or whatever you're designing.
However, sometimes you want to add some additional functionality to your struct so it works smoothly with other SwiftUI objects. For example, if you want to display your store inventory in a List()
, then you'll want your struct
to have a variable that makes one store item unique from all the others. This way the list knows which screwdriver your user tapped on.
To make your struct
unique, you make it conform to the Identifiable protocol! Identifiable
has one rule, your struct
must implement a var
named id
. That's it! Now your structure is Identifiable
.
Or maybe you have many workout structs
and you want to sort your list
of workout objects. How do you sort workouts? By muscle group? By difficulty? This is your problem to work out (ha! pun intended!). To allow SwiftUI
to compare two workouts, the struct
needs to implement the Comparable
protocol. This protocol has ONE rule. Your struct must implement a function to compare two Workout objects and return true
if the left hand object is "greater" than the right hand object.
Why doesn't Justin's View work?
You provide this code for your view:
struct TrackView: View {
let track: Track
}
Here you are saying that you have a struct
with one constant named track
of type Track
. But you are also saying your struct
conforms to the View
protocol. To conform to the View
protocol your struct
must implement a var
named body
! Furthermore, this var
named body
is a computed var
that must generate some kind of View
. This could be a Color
, a Text()
, a VStack()
, a NavigationStack()
or any one of the many types of views available via SwiftUI.
But the important part is: Your code is missing the var
named body
! This is required because you're declaring your struct
conforms to the View
protocol.
Keep coding!