Home > front end >  Protocol implementation on a class with @MainActor - how to avoid warnings?
Protocol implementation on a class with @MainActor - how to avoid warnings?

Time:01-27

If we have a simple protocol and class implementation like the following;

protocol Solution: ObservableObject {
   var result: String { get set }
   func calc() async
}

@MainActor
class Solve: Solution {
   @Published
   var result: String = ""

   func calc() async { // operate on actors to find the result
      result = "the answer" 
   }
}

Xcode will show a yellow warning : "Main actor-isolated property 'result' cannot be used to satisfy nonisolated protocol requirement" against the class definition of result.

Removing @MainActor will remove the warning, but then we need to manually Dispatch updates to result to ensure they are done on the main thread. Is there a cleaner way to do this? Perhaps by amending the protocol?

CodePudding user response:

Add MainActor to the protocol

@MainActor
protocol Solution: ObservableObject {
   var result: String { get set }
   func calc() async
}

I would give actor a look too, it all depends on the purpose of this class.

If its purpose is to update UI then wrapping the class is natural.

CodePudding user response:

The least intrusive solution is

@MainActor var result: String { get set }
  • Related