gpt4 book ai didi

ios - 如何获得一些闭包的总和

转载 作者:行者123 更新时间:2023-11-28 07:19:22 26 4
gpt4 key购买 nike

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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com