Search code examples
iosswiftasync-awaitswift-concurrency

withThrowingTaskGroup - No calls to throwing functions occur within 'try' expression


Problem:

I have the following function which shows a warning No calls to throwing functions occur within 'try' expression

Questions:

  • Why is this warning shown? (The code inside the task throws an error)
  • What should I do to propagate the error to the caller of f1?

Code:

func f1() async throws {
    try await withThrowingTaskGroup(of: Int.self) { group in //No calls to throwing functions occur within 'try' expression
        group.addTask(priority: .high) {
            throw NSError()
        }
    }
}

Solution

  • You indeed have not called any throwing functions, or thrown anything, in the withThrowingTaskGroup closure. You've just added a task for the group to run. This by itself won't throw anything. addTask is not marked throws, though its closure parameter is. It will only throw when you wait for the task's completion in one way or another.

    For example:

    try await group.waitForAll()
    

    Or if you want to loop through each task of the group:

    for try await someInt in group {
        // ...        
    }
    

    If you return something in the withThrowingTaskGroup closure, that's what withThrowingTaskGroup will return too. If you throw an error in the closure, withThrowingTaskGroup will throw that error (since it is rethrows), and so will f1.