Pogosito
(Pogos)
1
Hi swift forum!
I want to understand the ideas behind the following situations:
Situation 1
The method is marked as @MainActor in the protocol, but the implementation removed @MainActor.
protocol MainActorProtocol {
@MainActor func someFunc()
}
class NoMainActor: MainActorProtocol {
func someFunc() {
print("NoMainActor", Thread.current)
}
}
A variable of protocol type, why does it switch to the main thread at runtime ?
Why does the compiler allow to omit @MainActor in the implementation if the thread change occurs anyway ?
Task.detached {
let protocolTypeNoMainActor: MainActorProtocol = NoMainActor()
// RESULT: NoMainActor <_NSMainThread: 0x600001704000>{number = 1, name = main}
await protocolTypeNoMainActor.someFunc()
}
Situation 2
A method in the protocol is marked as @MainActor, but @MainActor was removed in the implementation.
The variable has a type of a specific class, for some reason the method still switches to the main thread and requires await to call it, although the implementation does not have @MainActor
Task.detached {
let noMainActor: NoMainActor = NoMainActor()
// RESULT: NoMainActor <_NSMainThread: 0x600001710000>{number = 1, name = main}
await noMainActor.someFunc()
}
Could you please explain the logic behind how this works ?