我试图根据条件从 for 循环中退出,但我遇到了这个问题,因为它甚至没有从循环中退出。这是我的代码的循环。
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()
}
}