我想在 swift 代码中执行以下操作:
我必须调用我的 api 才能更新多个项目。所以我异步调用每个项目的 api。每个 api 调用完成后都会执行一个回调函数。这些回调会减少一个计数器,因此当计数器达到 0 时,我知道我的所有 api 调用都已完成。当计数器达到 0 时,我想调用最终回调函数(一次,当所有调用完成时),以更新我的 UI 等等。这个最终回调在开始时传递到我的服务,并存储在类属性中供以后执行。
可执行 Playground 源:
// Playground - noun: a place where people can play
class MyService
{
let api = MyApi()
var storedFinalCallback: () -> Void = { arg in }
var queue: Int = 0
func update(items: [String], finalCallback: () -> Void )
{
// Count the necessary API calls
queue = items.count
// Store callback for later execution
storedFinalCallback = finalCallback
for item in items {
// Call api per item and pass queueCounter as async callback
api.updateCall(item, callback: self.callback())
}
}
func callback()
{
queue--
// Execute final callback when queue is empty
if queue == 0 {
println("Executing final callback")
storedFinalCallback()
}
}
}
class MyApi
{
func updateCall(item: String, callback: ())
{
println("Updating \(item)")
}
}
let myItems: [String] = ["Item1", "Item2", "Item3"]
let myInstance: MyService = MyService()
myInstance.update(myItems, finalCallback: {() -> Void in
println("Done")
})
问题在于这段代码最终回调的调用顺序错误。
显然回调函数已经执行但未正确传递。但是,这是我能够做到的唯一方法,没有编译器错误。
非常感谢任何帮助 - 我已经坚持了两天了。
最佳答案
我终于找到了工作代码:
// Playground - noun: a place where people can play
class MyService
{
let api = MyApi()
var storedFinalCallback: () -> Void = { arg in }
var queue: Int = 0
func update(items: [String], finalCallback: () -> Void )
{
// Count the necessary API calls
queue = items.count
// Store callback for later execution
storedFinalCallback = finalCallback
for item in items {
// Call api per item and pass queueCounter as async callback
api.updateCall(item, callback: self.callback)
}
}
func callback()
{
queue--
// Execute final callback when queue is empty
if queue == 0 {
println("Executing final callback")
storedFinalCallback()
}
}
}
class MyApi
{
func updateCall(item: String, callback: () -> Void)
{
println("Updating \(item)")
callback()
}
}
let myItems: [String] = ["Item1", "Item2", "Item3"]
let myInstance: MyService = MyService()
myInstance.update(myItems, finalCallback: {() -> Void in
println("Done")
})
关于swift - 在 Swift 中传递和存储闭包/回调,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29421523/