Annotating a closure as running on the main thread
Mar 3, 2022
Often times when you call a function with a closure as a parameter, you would like that closure to be run on the main thread for example:
func foo(_ completion: @escaping () -> Void) {
completion()
}
if you need your completion block to be run on the main thread you could use a dispatch queue
foo {
DispatchQueue.main.async {
print("Ran on main thread")
}
}
This is ok but then you’d have to remember to wrap it every time you use the foo function.
One way around this is to annotate that completion block with @MainActor
func bar(_ completion: @escaping @MainActor () -> Void) {
Task { await completion() }
}
This annotation will guarantee all users that the completion closure will be run on the main thread.
bar {
print("Will run on main thread. I guarantee it")
}