0

我试图根据条件从 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()
  }
}
4

2 回答 2

1

当前范围的return回报。

在这种情况下,它failureBlock: {}从 for 循环范围而不是从 for 循环范围返回。

您必须重构代码以实现您想要做的事情。

要么(如果此代码同步执行)您可以返回一个successtrue| false通过使function' 的返回类型Bool和删除failureBlock参数从函数中。

或者(如果此代码异步执行)您必须考虑在触发另一个任务之前等待一个任务完成/失败。

更新

我认为以下可能是此代码的简化版本-

var isFailure: Bool = false

func callTest(for item: Int) {
    print("task initiated \(item)")
    test(item: item, completion: {
        print("task succeeded \(item)")
        if item < 5 {
            callTest(for: item+1)
        } else {
            print("all tasks done")
        }
    }, failureBlock: {
        print("task failed \(item)")
    })
}

func test(item: Int, completion: @escaping (() -> Void), failureBlock: @escaping (() -> Void)) {
    Thread.sleep(forTimeInterval: TimeInterval(item))
    isFailure.toggle()
    if isFailure {
        failureBlock()
    } else {
        completion()
    }
}

callTest(for: 1)
于 2021-06-02T04:51:05.333 回答
0
var isFailure = false
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()
  })
  if isFailure == true {
    break
  }
  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()
  }
}```
Made few changes work like a charm.
Any one has better idea please comment
于 2021-06-02T06:43:37.313 回答