I made the mistake of upgrading my iPhone to iOS 15.4 to test out an app that required it. Then I could no longer build my apps to my iPhone, so I had to upgrade Xcode and now I'm getting this warning in all my apps.:
Expression requiring global actor 'MainActor' cannot appear in default-value expression of property '_vm'; this is an error in Swift 6
It's flagged yellow and doesn't stop me building or installing my apps. By looking online, I found the way to resolve it is changing:
@StateObject var vm = ListViewVM()
to
@StateObject var vm: ListViewVM
init() {
_vm = StateObject(wrappedValue: ListViewVM())
}
Although, the solution above works, it seems like it's a band-aid fix.
I have previously made all my classes like this:
@MainActor class ListViewVM: ObservableObject {
}
because Paul has said, paraphrased from my notes:
The MainActor is responsible for adding all user interface updates.
Adding the @MainActor attribute to our class means we want all the class in this code, unless we specifically ask otherwise, to run on the main actor.
This is really important because this thing is responsible for making UI updates and those must happen on the MainActor.
Swift silently infers @MainActor for @State and @StateObkect. It does not provide 100% safety. Code called from another class or struct could cause problems.
Every time you have a class that conforms to ObservableObject add @MainActor
Is this no longer the case? Should classes that conform to ObservableObject still have @MainActor added to them?
https://stackoverflow.com/questions/71396296/how-do-i-fix-expression-requiring-global-actor-mainactor-cannot-appear-in-def
https://stackoverflow.com/questions/71562257/xcode-keeps-throwing-a-swift-6-error-but-that-doesnt-exist