函数和闭包有什么区别? [英] What is the difference between functions and closures?

查看:35
本文介绍了函数和闭包有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在阅读 iBooks 中的 swift 编程指南.有人可以向我解释函数和闭包之间的区别吗?难道只是它没有名字,可以用在表达式中?

I have been reading the swift programming guide in iBooks. Could someone explain to me what is the difference between a function and a closure. Is it just that it has no name and can be used in expressions?

推荐答案

函数实际上只是命名的闭包.以下内容至少在概念上是等效的:

Functions are, in fact, just named closures. The following are at least conceptually equivalent:

let foo = { println("hello") }

func foo()->(){ println("hello") }

在使用 func 声明方法的情况下,这会变得稍微复杂一些,因为在自动插入公共命名参数等方面添加了一些有趣的糖. func myMethod例如,(foo:Int, bar:Int, baz:Int) 变为 func myMethod(foo:Int, #bar:Int, #baz:Int).

This gets a little more complicated in the case of using func to declare methods, as there's some interesting bits of sugar added regarding the automatic insertion of public named parameters, etc. func myMethod(foo:Int, bar:Int, baz:Int) becomes func myMethod(foo:Int, #bar:Int, #baz:Int), for example.

但即使方法也只是闭包的一种特殊情况,这仍然是正确的,如果闭包如此,那么函数和方法也是如此.

But it's still true that even methods are just a specific case of closures, and if it's true of closures, it's true of functions and methods as well.

这篇关于函数和闭包有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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