This is different than wanting to stop after a period of time. An example of possible use case:
func calculate(_ nums: [Int], _ target: Int, completion: @escaping (([Int]) -> Void)) {
let enumerated = nums.enumerated()
let queue = DispatchQueue.global(qos: .default)
let group = DispatchGroup()
var answer: [Int] = []
queue.async { () -> Void in
for (xIndex, xElement) in nums.enumerated() {
queue.async(group: group) {
for (yIndex, yElement) in enumerated where yIndex != xIndex {
if xElement + yElement == target {
answer = [xIndex, yIndex]
//I want it to end here
}
}
}
}
group.notify(queue: queue) {
completion(answer)
}
}
}
Here I am attaching each of the inner for loop to the dispatch group so they are calculating at the same time, but when the answer is found let's say in the 3rd for run, there is no need for the Dispatch group to calculate others and should stop like all the tasks are completed and call group.notify
Basically I want it to return
when it reaches the answer. Is there any way to do this? if so how?
From what I've researched, we can use group.leave
to explicitly say that a block in the group finished executing, but how can it be done so all the blocks in the group finish when we reach the desired point?