如何创build一个函数,最终返回一些数据,调用者必须等待

这实际上是一个Swift语言types的问题

我正在使用Firebase读取/写入数据

我想devise一个快速返回的例程, 最终返回。 调用者必须等待例程完成,所以它不是一个asynchronous的后台调用。 理想情况下,主叫方也应该能够:

  1. 确定成功或错误返回,并处理返回值

  2. 如果调用函数耗时太长,则等待超时

在这个function里面,hold-up只是Firebase的一个事件。 例如:

func eventuallyReturnFirebase() { //some stuff someObj.observeEventType(.ChildAdded, withBlock: { snapshot in print("\(snapshot.key) -> \(snapshot.value)") if (snapshot.key == "foo") { // we found value for foo } if (snapshot.key == "bar") { // we found value for bar } }) //now we can return foo and bar back to caller or some error if we did not } 

有人可以突出显示Swift语言在devise这样的function方面提供了什么,以及如何使用调用者? 希望也解决这两个理想的条件

如果您需要编写asynchronous调用的同步封装,则可以使用信号量。

也就是说,你可以写这样的东西(我省略了某些东西,比如types信息,所以它是一种类似于swift的伪代码,但是这应该足以得到这个想法):

 func eventuallyReturnFirebase() { let semaphore = dispatch_semaphore_create(0) //creating a "closed" semaphore var foo, bar //variables that will hold your return values someObj.observeEventType(.ChildAdded, withBlock: { snapshot in print("\(snapshot.key) -> \(snapshot.value)") if (snapshot.key == "foo") { // we found value for foo } if (snapshot.key == "bar") { // we found value for bar } //setting values for foo and bar foo = ... bar = ... dispatch_semaphore_signal(semaphore) // incrementing semaphore counter }) let timeout = dispatch_time(DISPATCH_TIME_NOW, DefaultTimeoutLengthInNanoSeconds) if dispatch_semaphore_wait(semaphore, timeout) != 0 { // waiting until semaphore conter becomes greater than 0 print("timed out") } return foo, bar } 

我build议看看NSCondition作为获得你想要的结果的一种方式。

被调用的例程启动一个定时器,启动一个asynchronous进程,然后在返回之前等待一个条件。 该条件是作为asynchronous处理的最后一个动作或通过定时器的触发而发出的。

一旦信号允许例程继续,就决定是因为时间还是要返回。