Swift - 通过块而不是return语句传回数据

时间:2015-04-13 06:49:16

标签: ios swift closures void clgeocoder

实际上我在这个链接中遇到了类似的情况:CLGeocoder in Swift - unable to return string when using reverseGeocodeLocation

很抱歉复制它,但是如何将字符串从完成块中传出来?


非常感谢你的帮助,Sergey Birukov

问题更新:更具体地说,我如何存储"结果"变量:"数据"?

func asyncFunctionToBeCalled(arg1: AnyObject, arg2: AnyObject, aBlock: (result: String) -> Void) -> Void { 
//As you can see, this function receives aBlock variable which should point to the block you want to execute once this function is done
var res: String!
aBlock(result)
}

var data = ""

asyncFunctionToBeCalled("a", "b", { (result: String) in
//This block will be called when asyncFunctionToBeCalled is executed
//variable "result" is your requested string here
data = result
})
println(data)

控制台输出什么

2 个答案:

答案 0 :(得分:3)

基本上异步是你要求其他人提前。为你购买杂货,这样你就可以继续编程,当他从商店回来时,你会收到杂货并将它放入冰箱。

实际例子:

// Correct way of implementing
asyncShopGrocieries(["Milk", "Cookies", "Potatoes"]) { groceries in
    fridge.insert(groceries)
}

// Incorrect way of implementing
var groceries:[String]!              // You create a variable

asyncShopGrocieries(["Milk", "Cookies", "Potatoes"])     // You make an async request
{ groceries in                      // Block that handles the data when done
    groceries = groceries_
}                                   // Block will execute after you reach the end of this function

fridge.insert(groceries)           // When you come here you will try to put the groceries inside the fridge while he is still on his way TO the store.

更新

class SomeClass {
    var groceries:[String]?
    var groceries2:[String]?
    var fridge = Fridge()



    func gotAllGroceries(groc: [String], groc2: [String]) {
        fridge.insert(self.groc, groc2)
    }

    func getGroceries() {
        asyncShopGrocieries(["Milk", "Cookies", "Potatoes"]) { groceries in
            self.groceries = groceries

            if groceries2 != nil {
                self.gotAllGroceries(self.groceries!, groc2: self.groceries2!)
            }
        }

        asyncShopGrocieries(["Candy", "Steak", "Apples"]) { groceries in
            self.groceries2 = groceries

            if groceries != nil {
                self.gotAllGroceries(self.groceries!, groc2: self.groceries2!)
            }
        }
    }
}

更新2

func async(time: UInt32, action: ()->()) {
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0)) {
        sleep(time)
        action()
    }
}


func testDispatchGroup() {
    let group = dispatch_group_create()

    let startDate = NSDate()

    dispatch_group_enter(group)
    async(2) {
        println("1 done")
        dispatch_group_leave(group)
    }

    dispatch_group_enter(group)
    async(1) {
        println("2 done")
        dispatch_group_leave(group)
    }

    dispatch_group_notify(group, dispatch_get_main_queue()) {
        println("Everything done!")

        println("Total time: \(NSDate().timeIntervalSinceDate(startDate))")
    }
}

打印出来:

2 done
1 done
Everything done!
Total time: 2.00842797756195

答案 1 :(得分:0)

您正在调用异步函数,它接收块作为参数。您应该使用您自己的块来调用此函数,该块接收字符串作为参数。因此,当异步功能完成时,它会使用结果字符串调用您的块。 例如:

func asyncFunctionToBeCalled(arg1: AnyObject, arg2: AnyObject, aBlock: (result: String) -> Void) -> Void {
  //As you can see, this function receives aBlock variable which should point to the block you want to execute once this function is done
  var res: String!
  //Some asynchronous code here which will call aBlock(result)
}

//Your calling code:
asyncFunctionToBeCalled("a", "b", { (result: String) in
   //This block will be called when asyncFunctionToBeCalled is executed
   //variable "result" is your requested string here
})