Best practice in official Persisting Data tutorial

I followed that Apple tutorial about persisting data using async/await and tasks (https://developer.apple.com/tutorials/app-dev-training/persisting-data), I have to say that everything works fine when following the tutorial, but I thought a bit about that code and wondered why is there a Task created in the (throwing async) load method ?

    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
    } 

Wouldn't it be better to just do the following ?

func load() async throws {
    let fileURL = try Self.fileURL()
    guard let data = try? Data(contentsOf: fileURL) else {
        return []
    }
    self.scrums = try JSONDecoder().decode([DailyScrum].self, from: data)
}

From my understanding, doing the later allow to remove one task schedule on the main thread. I don't really see the benefit to do it like it's shown in the tutorial.

If you have an argument that goes for the tutorial way, please let me know. If there's none found, why would Apple show some code that's more complex than necessary, and not best practice in its tutorials ?

Replies

Wouldn't it be better to just do the following?

That’s what I’d do (-:

There arguments to be made for loading file system data from a different task so that the load can run concurrently with whatever else you’re doing [1]. But that code then turns around and awaits the result of that task, so there’s no concurrency benefit anyway.

Please do file a bug against that tutorial, and post your bug number, just for the record.

Share and Enjoy

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

[1] Although there are arguments for not doing that as well, depending on your specific situation. Unlike with networking, the underlying file system implementation is entirely synchronous.

Thank you for the quick answer,

the bug number is FB12287183.

Now waiting for feedback on the issue.