I'm struggling with the following simplified scenario:
@MainActor
struct X: Equatable { // Main actor-isolated property 'y' can not be referenced from a nonisolated context
var y: Y = .init()
//static func ==(lhs: Self, rhs: Self) -> Bool { lhs.y == rhs.y }
}
public struct Y: Equatable {
public init() {}
}
Under Swift 5 language mode, we notice:
the synthesized conformance for the struct X to Equatable seems to be erroneous in the context of a @MainActor type.
providing a custom conformance to Equatable allows the code to compile
a warning is emitted that == should be nonisolated in order to conform to Equatable
adding nonisolated to the == function reveals the issue that the isolated state is inaccessible in a non-isolated context
removing the public from struct Y avoids the error entirely. Unclear why.
Ideally, I'd like == to operate within the actor-isolated context, but it doesn't seem that Equatable permits this. Consequently, it becomes quite challenging to implement the == operation safely when the state it depends on should be actor-isolated and the == function is non-async.
Further, it is my impression that under Swift 5 language mode, the synthesized conformance might simply emit the warning rather than trigger the error.
This is very similar to something posted a few threads down that you may find interesting: `func == ` vs MainActor
In Swift 6.2 you can conform to @MainActor Equatable to allow for this. This makes it so that you are not allowed to invoke == unless you are on the main actor. Until then you can just use @preconcurrency Equatable to silence the warning/error, but this will crash if you ever invoke == in a non-main actor context.
Thank you!
Can we identify any deficit in the synthesis of Equatable? eg. when conforming to Equatable rather than @MainActor Equatable, perhaps the synthesis should not carry an implicit nonisolated on ==, so we get the effect of the warning, where I implement == in the traditional sense.
Now the warning can be fixed by adding @MainActor to the Equatable conformance.
Certainly it would seem more natural for the Equatable conformance on an actor-isolated type to implicitly inherit this actor isolation, avoiding the noise of re-specifying that intent in each conformance of your type declarations, but presumably this was discussed elsewhere and decided against.
At a minimum the error could message could use some love to help guide the developer to the solution, as the situation is presently quite cryptic.