如何仅在 for-in 循环完成后使用 DispatchGroup 更新 UI

How to use DispatchGroup to update UI only after for-in loop has completed

当用户点击一个按钮时,会触发一个由 API 调用和计算组成的冗长函数。

@IBAction func buttonTapped(_ sender: Any) {
        
        var itemIndex = 0
        let dispatchGroup = DispatchGroup()
        
        for name in (entireRecipe?.extendedIngredients!)! {
            
            dispatchGroup.enter()
            
            CalculatorService().calculate() { item   in
                self.arrayItem.append(item)
                self.totalItems = self.arrayItems.reduce(0, +)
            }
            itemIndex = itemIndex + 1
        }
        dispatchGroup.leave()
        
        dispatchGroup.notify(queue: .main) {
            print("DispatchGroup Notified")
            self.itemLabel.text = "\(self.totalItems)"
        }
    }

我的上述理由是:

  1. dispatchGroup在for-in循环开始时进入
  2. dispatchGroup在for-in循环遍历整个数组后剩下
  3. dispatchGroup 才被通知,UI 标签被更新

但是,看起来 dispatchGroup.notify 并没有像预期的那样被 运行,因此 UI 标签在 for-in 循环完成后没有被更新。

我的 dispatchGroup 代码中是否缺少任何内容?非常感谢任何帮助!

leave 行必须 闭包内

for name in (entireRecipe?.extendedIngredients!)! {
    
    dispatchGroup.enter()
    
    CalculatorService().calculate() { item   in
        self.arrayItem.append(item)
        self.totalItems = self.arrayItems.reduce(0, +)
        dispatchGroup.leave()
    }
    itemIndex = itemIndex + 1
}