闭包和函数之间的差异作为参数在swift [英] Differrence between closure and function as argument in swift

查看:153
本文介绍了闭包和函数之间的差异作为参数在swift的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有近4年的Objective C和swift的新手的经验。我试图从目标C的角度理解swift的概念。所以如果我错了,请引导我:)



在目标c中,我们有块的代码,可以稍后异步执行),这使绝对完美的意义。但在swift中现在我们可以将一个函数作为参数传递给另一个函数,稍后可以执行,然后我们也关闭了。





根据 O'Reilly >



>



这是我的闭包

override func viewDidLoad(){
super.viewDidLoad()
//在加载视图之后执行任何其他设置,通常来自ni

let tempNumber :Int = 5

let numbers = [1,2,3,4,5]
print(numbers.map({$ 0 - tempNumber}))
}

变量tempNumber甚至在声明闭包之前被声明,但闭包有权限访问变量。现在,而不是地图,我尝试使用自定义类传递的闭包作为参数,并尝试执行相同的代码:)虽然现在闭包是在不同的范围执行,它仍然可以访问tempNumber。



我的结论是:closures可以访问在同一范围内声明的变量和方法,尽管它在不同的范围内被执行。 >

现在,不如将paramter作为参数传递,尝试将函数作为参数传递。

  class test {
func testFunctionAsParameter(testMethod:(Int) - > Int){
let seconds = 4.0
let delay = seconds * Double(NSEC_PER_SEC)// nanoseconds per seconds
let dispatchTime = dispatch_time(DISPATCH_TIME_NOW,Int64(delay))

dispatch_after(dispatchTime,dispatch_get_main_queue(),{
self.callLater(testMethod)
})
}

func callLater(testMethod:(Int) - > Int) - > Int {
return testMethod(100)
}
}

在不同的类中,我创建了一个Test实例,并使用它如下

  / *在不同类中* / 
override func viewDidLoad(){
super.viewDidLoad()
//在加载视图之后进行任何其他设置,通常来自ni

let tempAge:Int = 5

func test2(val:Int) - > Int {
return val - tempAge;
}

let testObj = test();
print(testObj.testFunctionAsParameter(test2))
}

称为测试,它有一个称为testFunctionAsParameter的方法,它又调用另一个方法callLater,最后这个方法执行传递的函数:)



现在所有这些马戏团,只是为了确保那个传递的方法在不同的范围执行)。



当我执行上面的代码:)我很震惊地看到即使函数作为参数传递,不同的范围,仍然可以访问在方法声明的相同范围内声明的变量testNumber)。



我总结:O'Reilly的声明当一个函数作为值传递,它携带其内部引用外部变量。 is bang on:)



现在我的疑问是苹果说函数是特殊情况的子句。我认为特殊情况必须与范围:)一些事情,但令我惊讶的代码显示,闭包和函数都可以访问外部作用域中的变量!!!!



其他,然后,语法不同如何闭包不同作为参数传递的函数?现在在内部必须有一些差异,否则苹果不会花费这么多的时间在设计它:)



如果没有范围?那么什么是不同的闭包和函数?? O'Reilly说:当一个函数作为一个值传递时,它会沿着它的内部引用到外部变量,这就是一个函数是一个闭包。所以它试图指出什么?该闭包不会引用外部变量?现在他们也不能错了吗?



我会疯狂地与苹果和O'Reilly的两个冲突的声明:(请帮助,我理解东西错误??请帮助我理解差异。

解决方案

在swift中,函数和闭包之间没有任何区别。



在Objective-C函数和块/闭包中ARE是一个匿名函数(一个没有名字的函数)不同。


I have almost 4 years of experience with Objective C and a newbie in swift. Am trying to understand the concept of swift from the perspective of Objective C. So if I am wrong please guide me through :)

In objective c, we have blocks (chunck of code which can be executed later asynchronously) which made absolutely perfect sense. But in swift now we can pass a function as a parameter to another function, which can be executed later, and then we have closure as well.

As per Apple "functions are special cases of clauses."

As per O'Reilly "when a function is passed around as a value, it carries along its internal references to external variables. That is what makes a function a closure."

So I tried a little bit to understand the same :)

Here is my closure

override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a ni

        let tempNumber : Int = 5

        let numbers = [1,2,3,4,5]
        print (numbers.map({ $0 - tempNumber}))
}

The variable tempNumber is declared even before the closure was declared, yet closure has the access to the variable. Now rather then a map, I tried using a custom class passed closure as a parameter and tried executing the same code :) Though now closure is getting executed in differrent scope, it still has the access to tempNumber.

I concluded : closures have an access to the variables and methods which are declared in the same scope as closure it self, though it gets execcuted in differrent scope.

Now rather then passing closure as paramter, tried passing function as a parameter,

class test {
    func testFunctionAsParameter(testMethod : (Int) -> Int){
        let seconds = 4.0
        let delay = seconds * Double(NSEC_PER_SEC)  // nanoseconds per seconds
        let dispatchTime = dispatch_time(DISPATCH_TIME_NOW, Int64(delay))

        dispatch_after(dispatchTime, dispatch_get_main_queue(), {
             self.callLater(testMethod)
        })
    }

    func callLater(testMethod : (Int) -> Int) -> Int {
        return testMethod(100)
    }
}

In a differrent class I created an instance of Test and used it as follow

/* in differrent class */
    override func viewDidLoad() {
            super.viewDidLoad()
            // Do any additional setup after loading the view, typically from a ni

            let tempAge : Int = 5

            func test2(val : Int) -> Int {
                return val - tempAge;
            }

            let testObj = test();
            print(testObj.testFunctionAsParameter(test2))
        }

Declared a class called test, which has a method called testFunctionAsParameter which in turn calls another method called callLater and finally this method executes the passed function :)

Now all these circus, just to ensure that passed method gets executed in differrent scope :)

When I executed the above code :) I was shocked to see that even though function passed as a parameter finally gets executed in different scope, still has the access to the variables testNumber that was declared at the same scope as the method declaration :)

I concluded : O'Reilly's statement "when a function is passed around as a value, it carries along its internal references to external variables." was bang on :)

Now my doubt is apple says functions are special cases of clauses. I thought special case must be something to do with scope :) But to my surprise code shows that both closure and function have access to variables in external scope !!!!

Other then, syntax differrence how closure is differrent from function passed as argument ??? Now there must be some differrence internally, otherwise Apple wouldn't have spent so much time in designing it :)

If not scope?? then what else is different in closure and function ?? O'Reilly states "when a function is passed around as a value, it carries along its internal references to external variables. That is what makes a function a closure." so what is it trying to point out ? that closure wont carry references to external variables ? Now they can't be wrong either, are they?

I am going mad with two conflicting statements from Apple and O'Reilly :( Please help, am I understanding something wrong ?? Please help me understand the difference.

解决方案

In swift there really isn't any difference between functions and closures. A closure is an anonymous function (A function with no name.) That's about it, other than the syntax differences you noted.

In Objective-C functions and blocks/closures ARE different.

这篇关于闭包和函数之间的差异作为参数在swift的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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