我正在尝试编写一系列函数,在要求用户确认某些内容之前验证用户的信息。 (想象一个购物应用程序)。
- 我首先必须检查用户是否添加了卡。
- 然后我必须检查他们是否有足够的余额。
- 然后我可以要求他们确认付款。
我可以编写异步方法来检查卡,例如......
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 允许以您想要的方式封装复杂的操作。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)