DispatchGroup逻辑工作流程 [英] DispatchGroup logical workflow

查看:43
本文介绍了DispatchGroup逻辑工作流程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试按以下方式实现 DispatchGroup ,但是如果第一个调用返回 true ,则第二个调用返回 false ,然后整体结果将返回 false .

I am trying to implement DispatchGroup as follows, but if the first call returns true, then the second one returns false, then overall result will return false.

但是,如果第一个调用返回 false ,则第二个调用返回 true ,则总体结果将返回 false ,这不是我预料到了.

However, if the first call returns false, then the second one returns true, then overall result will return false which is not what I expected.

如果任何调用返回 false ,我想返回 false .我该如何处理这个问题?

I want to return false, if any of the call returns false. How could I able to handle this issue?

 func storeInformation(id: String?, _ completion: @escaping (Bool) -> ()) {
    guard
      let id =  id
    else {
      completion(false)
      return
    }
    let dispatchGroup = DispatchGroup()
    var groupResult: Bool = false
    dispatchGroup.enter()
    storeFeatures { success in
      if success {
        groupResult = true
      } else {
        groupResult = false
      }
      dispatchGroup.leave()
    }
    
    dispatchGroup.enter()
    storeClasses { success in
      if success {
        groupResult = true
      } else {
        groupResult = false
      }
      dispatchGroup.leave()
    }
    dispatchGroup.notify(queue: .main) {
      completion(groupResult)
    }
  }

  private func storeClasses(_ completion: @escaping(Bool) -> Void) {
    postClasses { (error) in
      if let _ = error {
        completion(false)
      } else {
        completion(true)
      }
    }
  }

  private func storeFeatures(_ completion: @escaping(Bool) -> Void) {
    postFeatures { (error) in
      if let _ = error {
        completion(false)
      } else {
        completion(true)
      }
    }
  }

推荐答案

您有一个"AND"这里是语义的,因此您应该在代码中编写它:

You have an "AND" semantic here, so you should write that in your code:

let dispatchGroup = DispatchGroup()
var groupResult: Bool = true // identity for AND
dispatchGroup.enter()
storeFeatures { success in
  groupResult = groupResult && success // here!
  dispatchGroup.leave()
}

dispatchGroup.enter()
storeClasses { success in
  groupResult = groupResult && success // and here
  dispatchGroup.leave()
}
dispatchGroup.notify(queue: .main) {
  completion(groupResult)
}

每项任务完成后,您要表达这样的想法

When each task finishes, you want to express the idea that

如果前一个组的结果为true并且成功为true,则该组的结果应该为true

The group result should be true iff the previous group result is true AND success is true

这篇关于DispatchGroup逻辑工作流程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆