Array of async let

For async let, could we have an array? Like async let array = parts.map { download($0) }

hi Kai, this is done in section 2.8:

guard files.isEmpty else { return }

do {
  async let files = try model.availableFiles()
  async let status = try model.status()
} catch {
  lastErrorMessage = error.localizedDescription
}

files is an array of DownloadFile

Thanks @audrey for replying.
The code you paste is a little different. It return an Array by just decoding the data.

    guard let list = try? JSONDecoder().decode([DownloadFile].self, from: data) else {
      throw "The server respose was not recognized"
    }

In my case, it’s like

    let total = 4
    let parts = (0..<total).map { partInfo(index: $0, of: total) }

    async let part1 =
    downloadWithProgress(fileName: file.name, name: parts[0].name, size: parts[0].size, offset: parts[0].offset)
    async let part2 =
    downloadWithProgress(fileName: file.name, name: parts[1].name, size: parts[1].size, offset: parts[1].offset)
    async let part3 =
    downloadWithProgress(fileName: file.name, name: parts[2].name, size: parts[2].size, offset: parts[2].offset)
    async let part4 =
    downloadWithProgress(fileName: file.name, name: parts[3].name, size: parts[3].size, offset: parts[3].offset)

So, I feel it’s kind of duplicate. I want to use something like

async let array = try parts.map { } 

to simplify it. But I failed.

Is there anything using map to return an async array?

Hi Kai, if you need to have a dynamic amount of concurrency you should use task groups, discussed a little later in the book. async let is strictly for situations when you need concurrency for a fixed number of tasks, known at compile time.

1 Like