在Swift中链接多个异步函数

我正在尝试编写一系列function,在要求他们确认某些内容之前validation用户的信息。 (想象一下购物应用程序)。

  1. 我首先要检查用户是否添加了卡。
  2. 然后我必须检查他们是否有足够的平衡。
  3. 然后我可以要求他们确认付款。

我可以编写异步方法来检查卡片之类的东西……

func checkHasCard(completion: (Bool) -> ()) { // go to the inter webs // get the card // process data let hasCard: Bool = // the user has a card or not. completion(hasCard) } 

这可以像这样运行……

 checkHasCard { hasCard in if hasCard { print("YAY!") } else { print("BOO!") } } 

但是……现在,基于我必须做各种事情。 如果用户确实有卡,那么我需要继续前进并检查是否有足够的余额(以同样的方式)。 如果用户没有卡,我会出现一个屏幕,供他们添加卡。

但它变得凌乱……

 checkHasCard { hasCard in if hasCard { // check balance print("YAY!") checkBalance { hasBalance in if hasBalance { // WHAT IS GOING ON?! print("") } else { // ask to top up the account print("BOO!") } } } else { // ask for card details print("BOO!") } } 

我想要的是与此类似的东西……

 checkHasCard() // if no card then show card details screen .checkBalance() // only run if there is a card ... if no balance ask for top up .confirmPayment() 

这看起来更“狡猾”,但我不确定如何接近这样的事情。

有办法吗?

异步操作,有序和依赖? 你在描述NSOperation。

当然你可以使用GCD链接任务:

 DispatchQueue.main.async { // do something // check something... // and then: DispatchQueue.main.async { // receive info from higher closure // and so on } } 

但是如果你的操作很复杂,例如他们有代表,那么这种架构就会彻底崩溃。 NSOperation允许以您追求的方式封装复杂的操作。