WWDC22 SALE: Save 50% on all my Swift books and bundles! >>

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

   

Thanks.

   

Save 50% in my Black Friday sale.

SAVE 50% To celebrate WWDC22, all our books and bundles are half price, so you can take your Swift knowledge further without spending big! Get the Swift Power Pack to build your iOS career faster, get the Swift Platform Pack to builds apps for macOS, watchOS, and beyond, or get the Swift Plus Pack to learn advanced design patterns, testing skills, and more.

Save 50% on all our books and bundles!

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

Reply to this topic…

You need to create an account or log in to reply.

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.