2

问题:

我有以下显示警告的功能No calls to throwing functions occur within 'try' expression

问题:

  • 为什么显示此警告?(任务里面的代码会报错)
  • 我应该怎么做才能将错误传播给调用者f1

代码:

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()
        }
    }
}
4

1 回答 1

2

您确实没有在withThrowingTaskGroup闭包中调用任何抛出函数或抛出任何东西。您刚刚为组添加了要运行的任务。这本身不会抛出任何东西。addTask没有标记throws,尽管它的闭包参数是。它只会在您以一种或另一种方式等待任务完成时抛出。

例如:

try await group.waitForAll()

或者,如果您想遍历组的每个任务:

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

如果你在withThrowingTaskGroup闭包中返回一些东西,那withThrowingTaskGroup也将返回。如果你在闭包中抛出一个错误,withThrowingTaskGroup就会抛出那个错误(因为它是rethrows),所以f1.

于 2021-11-23T09:53:38.010 回答