I am trying to exit from for loop according to condition but I ran into the issue as it does not exit even from the loop. Here is a loop of my code.
var isFailure = true
let dispatchGroup = DispatchGroup()
var myFailureTask: Int?
for item in 1...5 {
dispatchGroup.enter()
test(item: item, completion: {
print("Success\(item)")
dispatchGroup.leave()
}, failureBlock: {
print("Failure\(item)")
myFailureTask = item
dispatchGroup.leave()
return
})
dispatchGroup.wait()
}
dispatchGroup.notify(queue: .main) {
if let myFailure = myFailureTask {
print("task failure \(myFailure)")
} else {
print("all task done")
}
}
func test(item: Int,completion: @escaping(() -> ()), failureBlock: @escaping(() -> ())) {
Thread.sleep(forTimeInterval: TimeInterval(item))
isFailure = !isFailure
if isFailure {
failureBlock()
} else {
completion()
}
}
The
return
returns from current scope.In this case it's returning from the
failureBlock: {}
and NOT from the for loop scope.You have to refactor the code to achieve what you are trying to do.
EITHER (in case this code is executing synchronously) you can return a
success
valuetrue
|false
from the function by makingfunction
's return typeBool
and removing thefailureBlock
argument.OR (in case this code is executing asynchronously) you have to think of waiting on one task to complete/fail before triggering the other.
UPDATE
I think following might be a simplified version of this code -