The need to use Task inside the declaration block of an asynchronous function

I am following the iOS App Dev Tutorials on Adopting Swift concurrency and Persisting data.

On Adopting Swift concurrency, it is mentioned that we can call an asynchronous function using the await keyword. Because the asynchronous function can suspend execution, we can use await only in asynchronous contexts, such as inside the body of another asynchronous function. Adopting Swift concurrency, it is also mentioned that we can create a new asynchronous context with a Task to call asynchronous functions from a synchronous context. Based on this information, I concluded that the main added value of a Task is to enable calling an asynchronous function in a synchronous context.

On Persisting data, a Task object is created inside the declaration block of an asynchronous function:

    func load() async throws {
        let task = Task<[DailyScrum], Error> {
            let fileURL = try Self.fileURL()
            guard let data = try? Data(contentsOf: fileURL) else {
                return []
            }
            let dailyScrums = try JSONDecoder().decode([DailyScrum].self, from: data)
            return dailyScrums
        }
        let scrums = try await task.value
        self.scrums = scrums
    }

I didn't understand why it was necessary to create task. Based on what I learned from Adopting Swift concurrency, the context of load() is already asynchronous. Therefore, we can simply call asynchronous functions without the need to create a Task object. When I tried to run the code by removing the task, the app still worked the same, or at least that was my perception.

I believe that there is another reason to use Task in this example other than just enabling calling asynchronous functions. However, this was not explicitly explained in the tutorials. Could you please explain why we use Task here? What is the added value and how it would improve the behavior of this app? Please keep in mind that I am a complete beginner and had no idea about what concurrency was two weeks ago.

In case deleting task would not change anything, could you please confirm that my initial understanding was correct?

Hmmm, this is very reminiscent of the issue discussed in this thread.

Share and Enjoy

Quinn “The Eskimo!” @ Developer Technical Support @ Apple
let myEmail = "eskimo" + "1" + "@" + "apple.com"

The need to use Task inside the declaration block of an asynchronous function
 
 
Q