-1

How can the following code be modified to print 2 after 1, without modifying the foo1() function?

func foo1() {
    Task {
        try await Task.sleep(nanoseconds: 1_000_000_000)
        print("1")
    }
}

func foo2() {
    print("2")
}

func mainFunc() {
    foo1()
    foo2()
}
mainFunc()

Edit: since I was asked I prefer to specify directly in the question. This is not a real problem, it's an exercise I set myself to improve the understanding of the language. I know there are alternative ways like using completion handlers (just to name one).

The answer to this question doesn't have to exist or be yes, it might just not be possible to take a function that launches a task and externally force its behavior synchronously.

Anyway this post may be helpful for someone who is planning to study concurrency in Swift

  • 3
    This sounds like an [XY Problem](http://xyproblem.info/). Why do you want to do this? Why can't you modify `foo1`? – Sweeper Jun 18 '23 at 03:43
  • If you are simply hesitating to modify `foo1` for fear of knock-on implications of code that is already using that function, consider refactoring it, keeping both the existing unstructured task interface (useful only for bridging from synchronous contexts) and introducing a new async interface. You don't have to break existing code when introducing the new `async` rendition. – Rob Jun 18 '23 at 12:46
  • The short answer to your question is that unless you have a rendition of `foo1` that is refactored to be an `async` function (or a completion handler or some other notification), no, you don’t have any way of knowing when that unstructured concurrency finishes. – Rob Jun 18 '23 at 22:57

1 Answers1

0

The simple answer is that you can't.

The main body of foo1 creates an unstructured task. You've provided no channel by which to monitor the Task and have not built in any mechanism to be notified of its completion.

Basically you've explicitly given up every opportunity to know when the Task in foo1 starts or when it completes.

Scott Thompson
  • 22,629
  • 4
  • 32
  • 34