Skip to content

Instantly share code, notes, and snippets.

@lslv1243
Last active October 10, 2023 12:14
Show Gist options
  • Save lslv1243/0b58fe62eedbdcaf905f3e253a8cd24c to your computer and use it in GitHub Desktop.
Save lslv1243/0b58fe62eedbdcaf905f3e253a8cd24c to your computer and use it in GitHub Desktop.
A test for the resolution of the `@MainActor` wrapper in Swift
import Foundation
protocol AProtocol {
func printIsMainThread()
}
struct AStruct: AProtocol {
@MainActor
func printIsMainThread() {
print("(struct) isMainThread=\(Thread.isMainThread)")
}
}
class AClass: AProtocol {
@MainActor
func printIsMainThread() {
print("(class) isMainThread=\(Thread.isMainThread)")
}
}
actor AnActor {
// by uncommenting the protocol type, the method will not be called on the main thread.
let aStructInstance/*: AProtocol*/ = AStruct()
let aClassInstance/*: AProtocol*/ = AClass()
func run() async {
await aStructInstance.printIsMainThread()
await aClassInstance.printIsMainThread()
}
}
@main
struct App {
static let anActorInstance = AnActor()
static func main() async {
await anActorInstance.run()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment