在Swift中传递和存储闭包/回调 [英] Passing and storing closures/callbacks in Swift

查看:190
本文介绍了在Swift中传递和存储闭包/回调的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在swift代码中执行以下操作:

I would like to do the following in swift code:

我必须调用我的api才能更新几个项目。所以我为每个项目异步调用api。每个api调用完成后都会执行一个回调函数。这些回调减少了一个计数器,所以当计数器达到0时,我知道我的所有api调用完成。当计数器达到0时,我想调用一个最终的回调函数(一次,当所有调用完成时),以便更新我的UI等等。

I have to call my api in order to update several items. So I call the api for each item asynchronously. Each api call executes a callback function when it's done. These callbacks decrease a counter, so that when the counter reaches 0 I know that all my api calls are completed. When the counter reaches 0 I would like to call a final callback function (once, when all calls are complete), in order to update my UI and so forth. This final callback is passes to my service in the beginning and stored in a class property for later execution.

可执行的Playground来源:

Executable Playground source:

// 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")
})

使用这个代码,最终的回调以错误的顺序被调用。

The problem is that with this code the final callback is called in the wrong order.

显然回调函数已经执行,没有正确传递。但是,这是我能够做到的唯一方法,没有编译器错误。

Apparently the callback function is already executed and not properly passed. However, this was the only way I was able to do it, without compiler errors.

任何帮助将非常感激 - 我一直坚持这两天了。

Any help would be really appreciated - I have been stuck on this for two days now.

推荐答案

我终于找到了工作代码:

I finally found the working code:

// 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中传递和存储闭包/回调的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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