Error in Challenge of lesson 8 Swift UI

There seems to be an error in challenge 8 of the Foundation Swift UI course

It says we should build a class where the topic of the lesson was a struct. When I use struct as a keyword, XCode will complain when I assign fuelLevel a new value like this is the method liftOff:

fuelLevel-=30 —> Cannot assign to property: ‘self’ is immutable

When I change from struct to class it does work. But that what not in the scope of the lesson.

Please advise why setting the property does not work in a struct.

Best

Armin

I know how to fix it in that way that I simply do a class instead of a struct. But I would like to know WHY it does not work in a struct, i.e. why properties behave differently.

But the course should have prepared with more care in the first place …

Structs are value types and classes are reference types. Among other differences between the two, this means that a function cannot change properties of a struct unless you prefix it with the mutating keyword.*

The Swift language guide page on Structures and Classes may give some more enlightenment on this topic.

* Note that this is not the case in SwiftUI for View properties marked as @State, even though View is a struct. That’s because the @State property wrapper causes that property to be stored outside the View's memory location and it is subsequently managed by the SwiftUI system itself. Which means, for one thing, that the property wrapped by @State gets persisted even when the View it belongs to is destroyed, which is how state is maintained.

1 Like

Hi Armin,

I have asked the CWC team if the Challenge 8 question is incorrect but have yet to receive a reply.

Classes are used in SwiftUI projects so I am not so sure that we should be jumping to conclusions that the challenge is incorrect or that the course has not been assembled with sufficient care.