Unexpected compiler error when trying to call sync function alongside async code

I'm trying to understand the reason for this unexpected compiler error I'm getting. Here is how to reproduce the issue:

  1. Make two functions with the same name - one sync and one async

  1. I can call each one separately.

I'm using the 'task' SwiftUI modifier which takes an async closure:

and

image

  1. But if I use any await in the task body, calling the sync version of the function produces compiler error. The compiler complains that I need to use 'await' with async functions. For example:

(The await call doesn't need to be to the same function, also a call to Task.sleep(...) trigger the compiler error)

I don't see the reason why I can't call the sync version - is this a bug or a feature?

What is .task? Is this a SwiftUI view?

1 Like

Yes, it's the task SwiftUI modifier - it takes an async closure

And what is the compiler error?

1 Like

Need to use 'await' when calling an async function (not on the laptop rn for the exact error)

Ah, ok. The issue is that the async version wins out in overload resolution. The workaround is explained in SE-0296—wrap the synchronous call in a closure:

func f() async {
  let f2 = {
    // In a synchronous context, the non-async overload is preferred:
    doSomething()
  }
  f2()
}
1 Like

Oh I see - it's covered by the last paragraph in that subsection; thanks for the link!