如何获得一些关闭的总和

如何获得一些关闭的总和

2个带有转义闭包的简单函数

func A(closure: @escaping (Int) -> () {
       //some delay
         closure(value1)
    }

func B(closure: @escaping (Int) -> () {
   //some delay
     closure(value2)
}

在其他函数中,我需要得到value1和value2的和
例如
func sum(completion: @escaping: (Int)->()){
     A(closure: { value1 in
        B(closure: { value2 in
           sum = value1 + value2
           completion(sum)
        })
     })
}

但是我不知道如果我需要对许多函数的结果求和该怎么办

最佳答案

您可以使用DispatchGroup

    func a(closure: @escaping (Int) -> ()) {
       //some delay
         closure(value1)
    }

    func b(closure: @escaping (Int) -> ()) {
       //some delay
         closure(value2)
    }

    func c(closure: @escaping (Int) -> ()) {
       //some delay
         closure(value3)
    }

    func sum(completion: @escaping: (Int)->()){
        let g = DispatchGroup()
        var sum = 0
         g.enter()
         a(closure: { value1 in
            sum += value1
            g.leave()
         })
         g.enter()
        b(closure: { value2 in
           sum += value2
           g.leave()
        })
         g.enter()
        c(closure: { value3 in
           sum += value3
           g.leave()
        })

        g.notify(queue: .main) {
            completion(sum)
        }

    }

关于ios - 如何获得一些关闭的总和,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/58578621/

10-12 21:28