在Swift中链接多个异步函数

Fog*_*ter 2 closures asynchronous ios swift

我正在尝试编写一系列函数来验证用户的信息,然后再要求他们确认.(想象一下购物应用).

  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)
}
Run Code Online (Sandbox Code Playgroud)

这可以像这样运行......

checkHasCard {
    hasCard in
    if hasCard {
        print("YAY!")
    } else {
        print("BOO!")
    }
}
Run Code Online (Sandbox Code Playgroud)

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

但它变得混乱......

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!")
    }
}
Run Code Online (Sandbox Code Playgroud)

相反,我想要的是......

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()
Run Code Online (Sandbox Code Playgroud)

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

有办法吗?

mat*_*att 6

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

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

DispatchQueue.main.async {
    // do something
    // check something...
    // and then:
    DispatchQueue.main.async {
        // receive info from higher closure
        // and so on
    }
}
Run Code Online (Sandbox Code Playgroud)

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