UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

SOLVED: Expression requiring global actor 'MainActor' cannot appear in default-value expression of property '_vm'; this is an error in Swift 6

Forums > SwiftUI

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

2      

Thanks.

2      

Hacking with Swift is sponsored by Essential Developer

SPONSORED Join a FREE crash course for mid/senior iOS devs who want to achieve an expert level of technical and practical skills – it’s the fast track to being a complete senior developer! Hurry up because it'll be available only until April 28th.

Click to save your free spot now

Sponsor Hacking with Swift and reach the world's largest Swift community!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.