Closures are self-contained blocks of functionality that can be passed
around and used in your code. Closures in Swift are similar to blocks
in C and Objective-C and to lambdas in other programming languages.
我以为是First-class functions的定义
他们也说:
Closures can capture and store references to any constants and
variables from the context in which they are defined. This is known as
closing over those constants and variables. Swift handles all of the
memory management of capturing for you.
我认为这是封闭的定义,而另一个定义是一流的功能,但苹果似乎把它们放在一起,称之为关闭.
// 'a' takes a first class function,which makes 'a' a higher order function func a(ch: () -> Void){ print("Something") ch() // 'ch' is a first class function print("Ended") } func closureFunc(){ var num = 2 a({ // access to 'num' is possible by closures num = num*2 print(num) }) } closureFunc()
>功能是一流的.这意味着它们可以传递 – 分配为变量,作为参数传递给函数参数,并作为结果传递给函数.
>函数是闭包.这意味着,在定义的时候,它们捕获函数体内所指的环境,但是在函数体之外被声明.
这是一个例子(从游乐场):
func multiplierMaker(i:Int) -> (Int) -> (Int) { func multiplier(ii:Int) -> (Int) { return ii*i } return multiplier } let g = multiplierMaker(10) g(2) // 20
想想功能乘数:
>乘数可以作为函数乘数Maker的结果返回,并分配给g,并且它有一个定义良好的类型(Int) – > (Int),是因为函数是一流的.
>当10被传递到multiplierMaker中时,由此产生的乘法器函数将其参数乘以10,即使分配给g并且稍后调用,这是因为函数是闭包.
(请注意,这与匿名函数无关,所有答案或语句导致您认为闭包与匿名函数有关是错误的,本示例中没有匿名函数,匿名函数是一个闭包,但只是因为所有功能都是关闭.)