闭包返回值(先前为completionBlock) [英] Closures return value (previously completionBlock)

查看:94
本文介绍了闭包返回值(先前为completionBlock)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在长期操作完成后返回一些值。
但是我还想分裂逻辑和gui。

I'd like to return some values after the long term operation is completed. But furthermore I'd like to split the logic and the gui.

例如;我有两个班级


  1. SomeServices.swift有一个名为getDataFromService ...的方法

  2. MyTableViewController.swift将显示getDataFromService的结果

所以,以前在Objective-C中我只是添加一个方法在SomeServices中,如下所示:

So, previously in Objective-C I've just add a method in SomeServices like this:

(void)getDataFromService:(void (^)(NSArray *, NSError *))completionBlock{ ...... }

在这个方法中,我刚刚调用了 completionBlock (myData,myError)将我的值返回到tableviewcontroller。

In this method I've just called completionBlock(myData, myError) to return my values to the tableviewcontroller.

我必须在SomeServices.swift中定义的等效闭包是什么如何在MyTableViewController中调用它?

What would be the equivalent closure which I have to define in SomeServices.swift and how will it be called in MyTableViewController?

我知道如何调用这样的简单闭包:

I know how to call a simple closures like this one:

   ....({
            responseData, error  in
            if(!error){
                //Do something
            }
        })

但我对如何定义一个与completionBlock等效的闭包没有任何想法。

But I don't have any ideas how to define a closure with a completionBlock equivalent.

任何帮助将不胜感激

推荐答案

关闭的优点是,你可以传递你想要的一切。方法或函数 - 没关系。

The plus of closures are, that you can pass everything you want. Methods or functions - it doesn't matter.

你可以在参数中传递一个函数并调用它。

You can pass a function within the parameters and just call it.

func someFunctionThatTakesAClosure(completionClosure: () -> ()) {
    // function body goes here
    if(error = false) {
       completionClosure()
    }

}

//Call it
someFunctionThatTakesAClosure({
    //Completions Stuff
    println("someFunctionThatTakesAClosure")
});

摘自:Apple Inc.The Swift Programming Language。iBooks。 https://itun.es/ch/jEUH0.l

Excerpt From: Apple Inc. "The Swift Programming Language." iBooks. https://itun.es/ch/jEUH0.l

这篇关于闭包返回值(先前为completionBlock)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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