Closures闭包
Group code that executes together, without creating a named function.
将执行的代码组合在一起,而不需要创建命名函数。
Closures are self-contained blocks of functionality that can be passed around and used in your code. Closures in Swift are similar to closures, anonymous functions, lambdas, and blocks in other programming languages.
闭包 是可以在你的代码中传递和使用的独立功能块。Swift 中的闭包类似于其他编程语言中的匿名函数、lambda 表达式和代码块。
Closures can capture and store references to any constants and variables from the context in which they're defined. This is known as closing over those constants and variables. Swift handles all of the memory management of capturing for you.
闭包可以捕获和存储其所在上下文中任意常量和变量的引用。这个过程可以看作是将这些常量和变量 包含 在闭包的作用域内。 Swift 会为你管理在捕获过程中涉及到的所有内存操作。
Note · 注意
Don't worry if you aren't familiar with the concept of capturing. It's explained in detail below in Capturing Values.
如果你不熟悉捕获(capturing)这个概念也不用担心。 在 值捕获 章节有它更详细的介绍。
Global and nested functions, as introduced in Functions, are actually special cases of closures. Closures take one of three forms:
在 函数 章节中介绍的全局和嵌套函数实际上也是特殊的闭包,闭包采用如下三种形式之一:
- Global functions are closures that have a name and don't capture any values.
- Nested functions are closures that have a name and can capture values from their enclosing function.
- Closure expressions are unnamed closures written in a lightweight syntax that can capture values from their surrounding context.
- 全局函数是一个有名字但不会捕获任何值的闭包
- 嵌套函数是一个有名字并可以捕获其封闭函数域内值的闭包
- 闭包表达式是使用轻量级语法编写的匿名闭包,它们能够捕获其上下文中的值。
Swift's closure expressions have a clean, clear style, with optimizations that encourage brief, clutter-free syntax in common scenarios. These optimizations include:
Swift 中的闭包表达式风格简洁明了,通过一系列优化,使得在常见的情况下可以写出简短而清晰的代码。主要优化如下:
- Inferring parameter and return value types from context
- Implicit returns from single-expression closures
- Shorthand argument names
- Trailing closure syntax
- 利用上下文推断参数和返回值类型
- 单表达式闭包的隐式返回(可以省略 return 关键字)
- 简化参数名称
- 尾随闭包语法
Closure Expressions 闭包表达式
Nested functions, as introduced in Nested Functions, are a convenient means of naming and defining self-contained blocks of code as part of a larger function. However, it's sometimes useful to write shorter versions of function-like constructs without a full declaration and name. This is particularly true when you work with functions or methods that take functions as one or more of their arguments.
在 嵌套函数 中介绍的嵌套函数,提供了一种便捷的方式,可以在较大的函数内部命名和定义自包含的代码块。然而,有时我们需要更简洁的函数式结构,而不必完整地声明函数名称。这在处理那些接受函数作为参数的函数或方法时特别有用。
Closure expressions are a way to write inline closures in a brief, focused syntax.
Closure expressions provide several syntax optimizations
for writing closures in a shortened form without loss of clarity or intent.
The closure expression examples below illustrate these optimizations
by refining a single example of the sorted(by:) method over several iterations,
each of which expresses the same functionality in a more succinct way.
闭包表达式 是一种以简短、集中的语法编写内联闭包的方法。在保证不丢失它语法清晰和意图的同时,闭包表达式提供了几种优化的语法简写形式。下面的闭包表达式通过对 sorted(by:) 这一示例的多次迭代来展示这个过程,每次迭代都使用了更加简洁的方式描述了相同功能。
The Sorted Method Sorted 方法
Swift's standard library provides a method called sorted(by:),
which sorts an array of values of a known type,
based on the output of a sorting closure that you provide.
Once it completes the sorting process,
the sorted(by:) method returns a new array of the same type and size as the old one,
with its elements in the correct sorted order.
The original array isn't modified by the sorted(by:) method.
Swift 标准库提供了名为 sorted(by:) 的方法,它会基于你提供的排序闭包表达式的判断结果对数组中的值(类型确定)进行排序。一旦它完成排序过程,sorted(by:) 方法会返回一个与旧数组类型大小相同类型的新数组,该数组的元素有着正确的排序顺序。原数组不会被 sorted(by:) 方法修改。
The closure expression examples below use the sorted(by:) method
to sort an array of String values in reverse alphabetical order.
Here's the initial array to be sorted:
下面的闭包表达式示例使用 sorted(by:) 方法对一个 String 类型的数组进行字母逆序排序。以下是初始数组:
let names = ["Chris", "Alex", "Ewa", "Barry", "Daniella"]The sorted(by:) method accepts a closure that takes two arguments
of the same type as the array's contents,
and returns a Bool value to say whether the first value should appear
before or after the second value once the values are sorted.
The sorting closure needs to return true
if the first value should appear before the second value,
and false otherwise.
sorted(by:) 方法接受一个闭包,该闭包需要传入与数组元素类型相同的两个实参,并返回一个 Bool 值,来表明排序后第一个值应该排在第二个值前面还是后面。如果第一个值应该出现在第二个值前面,排序闭包需要返回 true,否则返回 false。
This example is sorting an array of String values,
and so the sorting closure needs to be a function of type (String, String) -> Bool.
该例子对一个 String 类型的数组进行排序,因此排序闭包函数类型需为 (String, String) -> Bool。
One way to provide the sorting closure is to write a normal function of the correct type,
and to pass it in as an argument to the sorted(by:) method:
提供排序闭包函数的一种方式是编写一个正确类型的普通函数,并将其作为 sorted(by:) 方法的参数传入:
func backward(_ s1: String, _ s2: String) -> Bool {
return s1 > s2
}
var reversedNames = names.sorted(by: backward)
// reversedNames is equal to ["Ewa", "Daniella", "Chris", "Barry", "Alex"]If the first string (s1) is greater than the second string (s2),
the backward(_:_:) function will return true,
indicating that s1 should appear before s2 in the sorted array.
For characters in strings,
“greater than” means “appears later in the alphabet than”.
This means that the letter "B" is “greater than” the letter "A",
and the string "Tom" is greater than the string "Tim".
This gives a reverse alphabetical sort,
with "Barry" being placed before "Alex", and so on.
如果第一个字符串 ( s1 ) 大于第二个字符串 ( s2 ),backward(_:_:) 函数将返回 true,表示在新的数组中 s1 应该出现在 s2 前。对于字符串中的字符,“大于”表示“在字母顺序较晚出现”。这意味着字母 "B" “大于”字母 "A",字符串 "Tom" 大于字符串 "Tim"。这给出了一个字母逆序排序,将 "Barry" 放在 "Alex" 之前,依此类推。
However, this is a rather long-winded way to write
what is essentially a single-expression function (a > b).
In this example, it would be preferable to write the sorting closure inline,
using closure expression syntax.
然而,这是一种相当繁琐的编写方式,本质上是一个单表达式函数 (a > b)。对于这个例子来说,利用闭包表达式语法可以更好地构造一个内联排序闭包。
Closure Expression Syntax 闭包表达式语法
Closure expression syntax has the following general form:
闭包表达式语法的一般形式如下:
{ (<#parameters#>) -> <#return type#> in
<#statements#>
}The parameters in closure expression syntax can be in-out parameters, but they can't have a default value. Variadic parameters can be used if you name the variadic parameter. Tuples can also be used as parameter types and return types.
闭包表达式语法中的 参数 可以是 in-out 参数,但不能具有默认值。如果你命名了可变参数,也可以使用可变参数。元组也可以用作参数类型和返回类型。
The example below shows a closure expression version of the backward(_:_:) function
from above:
下面的示例展示了上面的 backward(_:_:) 函数对应的闭包表达式版本:
reversedNames = names.sorted(by: { (s1: String, s2: String) -> Bool in
return s1 > s2
})Note that the declaration of parameters and return type for this inline closure
is identical to the declaration from the backward(_:_:) function.
In both cases, it's written as (s1: String, s2: String) -> Bool.
However, for the inline closure expression,
the parameters and return type are written inside the curly braces,
not outside of them.
需要注意的是,内联闭包的参数和返回类型的声明与 backward(_:_:) 函数的声明相同。在这两种情况下,它都写为 (s1: String, s2: String) -> Bool。但是在内联闭包表达式中,参数和返回类型都写入 大括号 内,而不是大括号外。
The start of the closure's body is introduced by the in keyword.
This keyword indicates that
the definition of the closure's parameters and return type has finished,
and the body of the closure is about to begin.
闭包函数主体的开始以 in 关键字开始。这个关键字表示闭包的参数和返回类型定义已经结束,接下来是闭包的实际内容。
Because the body of the closure is so short, it can even be written on a single line:
因为闭包的主体很短,甚至可以写在一行上:
reversedNames = names.sorted(by: { (s1: String, s2: String) -> Bool in return s1 > s2 } )This illustrates that the overall call to the sorted(by:) method has remained the same.
A pair of parentheses still wrap the entire argument for the method.
However, that argument is now an inline closure.
这说明对 sorted(by:) 方法的整体调用保持不变。一对括号仍然包裹着方法的整个参数。然而,参数现在变为了内联闭包。
Inferring Type From Context 根据上下文推断类型
Because the sorting closure is passed as an argument to a method,
Swift can infer the types of its parameters
and the type of the value it returns.
The sorted(by:) method is being called on an array of strings,
so its argument must be a function of type (String, String) -> Bool.
This means that the (String, String) and Bool types don't need to be written
as part of the closure expression's definition.
Because all of the types can be inferred,
the return arrow (->) and the parentheses around the names of the parameters
can also be omitted:
因为排序闭包是作为参数传递给方法的,所以 Swift 可以推断其参数的类型和返回的值的类型。sorted(by:) 方法被一个字符串数组调用,因此其参数必须是 (String, String) -> Bool 类型的函数。这意味着 (String, String) 和 Bool 类型不需要作为闭包表达式定义的一部分。由于可以推断所有类型,因此也可以省略返回箭头 ( -> ) 和参数名称两边的括号:
reversedNames = names.sorted(by: { s1, s2 in return s1 > s2 } )It's always possible to infer the parameter types and return type when passing a closure to a function or method as an inline closure expression. As a result, you never need to write an inline closure in its fullest form when the closure is used as a function or method argument.
当将闭包作为内联表达式传递给函数或方法时,Swift 通常能够推断出参数类型和返回类型。这意味着,在使用闭包作为函数或方法参数时,你不必写出完整的闭包形式。
Nonetheless, you can still make the types explicit if you wish,
and doing so is encouraged if it avoids ambiguity for readers of your code.
In the case of the sorted(by:) method,
the purpose of the closure is clear from the fact that sorting is taking place,
and it's safe for a reader to assume that
the closure is likely to be working with String values,
because it's assisting with the sorting of an array of strings.
不过,如果你希望让代码更加清晰,也可以显式地声明类型。特别是当这样做能避免给读者造成歧义时,我们鼓励这种做法。以 sorted(by:) 方法为例,从排序这个操作就可以清楚地看出闭包的用途。读者可以安全地假设这个闭包很可能在处理 String 类型的值,因为它是用来协助对字符串数组进行排序的。
Implicit Returns from Single-Expression Closures 单表达式闭包的隐式返回
Single-expression closures can implicitly return the result of their single expression
by omitting the return keyword from their declaration,
as in this version of the previous example:
单表达式闭包可以通过从其声明中省略 return 关键字来隐式返回其单表达式的结果,如上版本的例子可以改写为:
reversedNames = names.sorted(by: { s1, s2 in s1 > s2 } )Here, the function type of the sorted(by:) method's argument
makes it clear that a Bool value must be returned by the closure.
Because the closure's body contains a single expression (s1 > s2)
that returns a Bool value,
there's no ambiguity, and the return keyword can be omitted.
在这个例子中,sorted(by:) 方法的参数类型明确了闭包必须返回一个 Bool 值。因为闭包的主体包含了一个返回 Bool 值的单个表达式 ( s1 > s2 ),因此不存在歧义,并且可以省略 return 关键字。
Shorthand Argument Names 简写参数名称
Swift automatically provides shorthand argument names to inline closures,
which can be used to refer to the values of the closure's arguments
by the names $0, $1, $2, and so on.
Swift 自动为内联闭包提供了简写参数名称功能,你可以直接通过 $0、$1、$2 等来引用闭包参数的值,以此类推。
If you use these shorthand argument names within your closure expression,
you can omit the closure's argument list from its definition.
The type of the shorthand argument names
is inferred from the expected function type,
and the highest numbered shorthand argument you use
determines the number of arguments that the closure takes.
The in keyword can also be omitted,
because the closure expression is made up entirely of its body:
如果在闭包表达式中使用这些简写参数名,你可以省略闭包定义中的参数列表。Swift 会根据函数的预期类型来推断出这些简写参数的类型。你使用的最大编号的简写参数决定了闭包接受的参数数量。由于此时闭包表达式仅由其函数体组成,因此 in 关键字也可以省略:
reversedNames = names.sorted(by: { $0 > $1 } )Here, $0 and $1 refer to the closure's first and second String arguments.
Because $1 is the shorthand argument with highest number,
the closure is understood to take two arguments.
Because the sorted(by:) function here expects a closure
whose arguments are both strings,
the shorthand arguments $0 and $1 are both of type String.
在这个例子中,$0 和 $1 表示闭包的第一个和第二个 String 参数。由于 $1 是编号最大的简写参数,因此闭包可以理解为需要两个参数。因为这里的 sorted(by:) 函数需要一个参数都是字符串的闭包,所以简写参数 $0 和 $1 都是 String 类型。
Operator Methods 运算符方法
There's actually an even shorter way to write the closure expression above.
Swift's String type defines its string-specific implementation of
the greater-than operator (>)
as a method that has two parameters of type String,
and returns a value of type Bool.
This exactly matches the method type needed by the sorted(by:) method.
Therefore, you can simply pass in the greater-than operator,
and Swift will infer that you want to use its string-specific implementation:
实际上有一种 更短 的方法来编写上面的闭包表达式。Swift 的 String 类型定义了关于大于运算符 ( > ) 的字符串实现方法,该方法具有两个 String 类型的参数,并返回一个 Bool 类型的值。这正好符合 sorted(by:) 方法所需的函数类型。因此,你可以直接传入大于运算符,Swift 会推断出你想使用它的字符串特定实现:
reversedNames = names.sorted(by: >)For more about operator methods, see Operator Methods.
更多关于运算符方法的内容请查看 运算符方法.
Trailing Closures 尾随闭包
If you need to pass a closure expression to a function as the function's final argument and the closure expression is long, it can be useful to write it as a trailing closure instead. You write a trailing closure after the function call's parentheses, even though the trailing closure is still an argument to the function. When you use the trailing closure syntax, you don't write the argument label for the first closure as part of the function call. A function call can include multiple trailing closures; however, the first few examples below use a single trailing closure.
如果你需要将闭包表达式作为函数的最后一个参数传递给函数,并且闭包表达式很长,则将其编写为 尾随闭包 的形式可能会很有用。在函数调用的括号后编写一个尾随闭包,该尾随闭包仍然会作为该函数的一个参数。使用尾随闭包语法时,不用在函数调用过程中为第一个闭包声明参数名。函数调用可以包含多个尾随闭包;但是,下面的前几个示例只使用了单个尾随闭包。
func someFunctionThatTakesAClosure(closure: () -> Void) {
// function body goes here
}
// Here's how you call this function without using a trailing closure:
someFunctionThatTakesAClosure(closure: {
// closure's body goes here
})
// Here's how you call this function with a trailing closure instead:
someFunctionThatTakesAClosure() {
// trailing closure's body goes here
}The string-sorting closure from the Closure Expression Syntax section above
can be written outside of the sorted(by:) method's parentheses as a trailing closure:
上面 闭包表达式语法 部分的字符串排序闭包可以写在 sorted(by:) 方法的括号之外作为尾随闭包:
reversedNames = names.sorted() { $0 > $1 }If a closure expression is provided as the function's or method's only argument
and you provide that expression as a trailing closure,
you don't need to write a pair of parentheses ()
after the function or method's name when you call the function:
如果一个闭包表达式是函数或方法的唯一参数,并且把该表达式写作尾随闭包,则在调用函数或方法时,无需在函数名或方法名后编写一对括号 () :
reversedNames = names.sorted { $0 > $1 }Trailing closures are most useful when the closure is sufficiently long that
it isn't possible to write it inline on a single line.
As an example, Swift's Array type has a map(_:) method,
which takes a closure expression as its single argument.
The closure is called once for each item in the array,
and returns an alternative mapped value (possibly of some other type) for that item.
You specify
the nature of the mapping and the type of the returned value
by writing code in the closure that you pass to map(_:).
当闭包足够长以至于无法在单行上内联写入时,尾随闭包变得非常有用。例如,Swift 的 Array 类型有一个 map(_:) 方法,该方法将闭包表达式作为其唯一参数。对于数组中的每一个元素,都将调用一次闭包,并返回该元素的映射值(可能是其他类型的)。你可以通过在传递给 map(_:) 的闭包中编写代码来指定映射的性质和返回值的类型。
After applying the provided closure to each array element,
the map(_:) method returns a new array containing all of the new mapped values,
in the same order as their corresponding values in the original array.
将提供的闭包应用于每个数组元素后,map(_:) 方法返回一个新数组,其中包含了所有新的映射值,其顺序与原始数组中的相应值相同。
Here's how you can use the map(_:) method with a trailing closure
to convert an array of Int values into an array of String values.
The array [16, 58, 510] is used to create the new array
["OneSix", "FiveEight", "FiveOneZero"]:
下例是如何使用带有尾随闭包的 map(_:) 方法将 Int 类型数组转换为 String 类型数组。数组 [16, 58, 510] 用于创建新的数组 ["OneSix", "FiveEight", "FiveOneZero"] :
let digitNames = [
0: "Zero", 1: "One", 2: "Two", 3: "Three", 4: "Four",
5: "Five", 6: "Six", 7: "Seven", 8: "Eight", 9: "Nine"
]
let numbers = [16, 58, 510]The code above creates a dictionary of mappings between the integer digits and English-language versions of their names. It also defines an array of integers, ready to be converted into strings.
上面的代码创建了一个整型数位和它们英文版本名字相映射的字典。同时还定义了一个准备转换为字符串数组的整型数组。
You can now use the numbers array to create an array of String values,
by passing a closure expression to the array's map(_:) method as a trailing closure:
你现在可以通过将一个闭包表达式作为尾随闭包传递给数组的 map(_:) 方法, 来使用 numbers 数组创建一个 String 类型的数组。
let strings = numbers.map { (number) -> String in
var number = number
var output = ""
repeat {
output = digitNames[number % 10]! + output
number /= 10
} while number > 0
return output
}
// strings is inferred to be of type [String]
// its value is ["OneSix", "FiveEight", "FiveOneZero"]The map(_:) method calls the closure expression once for each item in the array.
You don't need to specify the type of the closure's input parameter, number,
because the type can be inferred from the values in the array to be mapped.
map(_:) 方法为数组中的每个元素调用一次闭包表达式。你无需指定闭包的输入参数 number 的类型,因为可以从要映射的数组类型进行推断。
In this example,
the variable number is initialized with the value of the closure's number parameter,
so that the value can be modified within the closure body.
(The parameters to functions and closures are always constants.)
The closure expression also specifies a return type of String,
to indicate the type that will be stored in the mapped output array.
在这个例子中,变量 number 被初始化为闭包参数 number 的值,这样就可以在闭包内部修改这个值。(注意,函数和闭包的参数本身总是常量。)闭包表达式还指定了 String 作为返回类型,表明映射后的新数组将存储字符串类型的值。
The closure expression builds a string called output each time it's called.
It calculates the last digit of number by using the remainder operator (number % 10),
and uses this digit to look up an appropriate string in the digitNames dictionary.
The closure can be used to create a string representation of any integer greater than zero.
闭包表达式每次调用时都会生成一个名为 output 的字符串。它使用求余运算符 ( number % 10 ) 计算 number 的最后一位数字,并使用此数字在 digitNames 字典中查找所映射的字符串。这个闭包可用于创建任何一个大于零的整数的字符串表示形式。
Note · 注意
The call to the digitNames dictionary's subscript
is followed by an exclamation point (!),
because dictionary subscripts return an optional value
to indicate that the dictionary lookup can fail if the key doesn't exist.
In the example above, it's guaranteed that number % 10
will always be a valid subscript key for the digitNames dictionary,
and so an exclamation point is used to force-unwrap the String value
stored in the subscript's optional return value.
对 digitNames 字典的下标访问后面跟着一个感叹号(!),这是因为字典的下标返回一个可选值,表示如果键不存在,字典查找可能会失败。在上面的例子中,可以保证 number % 10 总是 digitNames 字典的有效下标键,所以使用感叹号来强制解包下标的可选返回值中存储的 String 值。
The string retrieved from the digitNames dictionary
is added to the front of output,
effectively building a string version of the number in reverse.
(The expression number % 10 gives a value of
6 for 16, 8 for 58, and 0 for 510.)
从 digitNames 字典中获取的字符串会被添加到 output 的开头,这样就巧妙地实现了数字的反向字符串构建。(例如,number % 10 的计算结果:对于 16 得到 6,对于 58 得到 8,对于 510 得到 0。)
The number variable is then divided by 10.
Because it's an integer, it's rounded down during the division,
so 16 becomes 1, 58 becomes 5, and 510 becomes 51.
然后将 number 变量除以 10。因为它是一个整数,所以在除法过程中会向下舍入,所以 16 变成 1 , 58 变成 5 , 510 变成 51 。
The process is repeated until number is equal to 0,
at which point the output string is returned by the closure,
and is added to the output array by the map(_:) method.
重复该过程,直到 number 等于 0,此时闭包返回 output 字符串,并通过 map(_:) 方法添加到输出到映射数组中。
The use of trailing closure syntax in the example above
neatly encapsulates the closure's functionality
immediately after the function that closure supports,
without needing to wrap the entire closure within
the map(_:) method's outer parentheses.
在上面的示例中使用尾随闭包语法,巧妙地在函数后封装了闭包的具体功能,而无需将整个闭包包裹在 map(_:) 方法的外括号中。
If a function takes multiple closures, you omit the argument label for the first trailing closure and you label the remaining trailing closures. For example, the function below loads a picture for a photo gallery:
如果一个函数采用多个闭包,则省略第一个尾随闭包的参数名,并声明其余的尾随闭包。例如,以下函数将为照片库加载图片:
func loadPicture(from server: Server, completion: (Picture) -> Void, onFailure: () -> Void) {
if let picture = download("photo.jpg", from: server) {
completion(picture)
} else {
onFailure()
}
}When you call this function to load a picture, you provide two closures. The first closure is a completion handler that displays a picture after a successful download. The second closure is an error handler that displays an error to the user.
当你调用此函数来加载图片时,将提供两个闭包。第一个闭包是一个完成处理程序,在成功下载后显示图片。第二个闭包是一个错误处理程序,用于向用户显示错误。
loadPicture(from: someServer) { picture in
someView.currentPicture = picture
} onFailure: {
print("Couldn't download the next picture.")
}In this example,
the loadPicture(from:completion:onFailure:) function
dispatches its network task into the background,
and calls one of the two completion handlers when the network task finishes.
Writing the function this way lets you cleanly separate the code
that's responsible for handling a network failure
from the code that updates the user interface after a successful download,
instead of using just one closure that handles both circumstances.
在此示例中,loadPicture(from:completion:onFailure:) 函数将其网络任务分配到后台,并在网络任务完成时调用两个完成处理程序之一。通过这种方法编写函数,可以清楚地将负责处理网络故障的代码与在成功下载后更新用户界面的代码分开,而不是只使用一个闭包处理两种情况。
Note · 注意
Completion handlers can become hard to read, especially when you have to nest multiple handlers. An alternate approach is to use asynchronous code, as described in Concurrency.
(完成处理)Completion handlers 可能会变得难以阅读,特别是当你需要嵌套多个处理时。一种替代方法是使用异步代码,详情请参阅 并发 章节。
Capturing Values 值捕获
A closure can capture constants and variables from the surrounding context in which it's defined. The closure can then refer to and modify the values of those constants and variables from within its body, even if the original scope that defined the constants and variables no longer exists.
闭包可以从定义它的环境上下文中 捕获 常量和变量。即使定义这些常量和变量的原作用域已经不存在,闭包仍然可以在闭包函数体内引用和修改这些值。
In Swift, the simplest form of a closure that can capture values is a nested function, written within the body of another function. A nested function can capture any of its outer function's arguments and can also capture any constants and variables defined within the outer function.
在 Swift 中,可以捕获值的最简单的闭包形式是嵌套函数,它编写在另一个函数体中。嵌套函数可以捕获其外部函数的任何参数,也可以捕获在外部函数中定义的任何常量和变量。
Here's an example of a function called makeIncrementer,
which contains a nested function called incrementer.
The nested incrementer() function captures two values,
runningTotal and amount,
from its surrounding context.
After capturing these values,
incrementer is returned by makeIncrementer as a closure
that increments runningTotal by amount each time it's called.
下面是一个名为 makeIncrementer 的函数的例子,它包含一个名为 incrementer 的嵌套函数。嵌套函数 incrementer() 从上下文中捕获了两个值:runningTotal 和 amount。捕获这些值之后,makeIncrementer 将 incrementer 作为闭包返回,每次调用 incrementer 时,它都会将 runningTotal 增加 amount。
func makeIncrementer(forIncrement amount: Int) -> () -> Int {
var runningTotal = 0
func incrementer() -> Int {
runningTotal += amount
return runningTotal
}
return incrementer
}The return type of makeIncrementer is () -> Int.
This means that it returns a function, rather than a simple value.
The function it returns has no parameters,
and returns an Int value each time it's called.
To learn how functions can return other functions,
see Function Types as Return Types.
makeIncrementer 的返回类型为 () -> Int。这意味着它返回一个 函数,而不是一个简单的值。它返回的函数没有参数,每次调用它时都返回一个 Int 值。要了解函数如何返回其他函数,请参阅 函数类型作为返回类型 。
The makeIncrementer(forIncrement:) function defines an integer variable called runningTotal,
to store the current running total of the incrementer that will be returned.
This variable is initialized with a value of 0.
makeIncrementer(forIncrement:) 函数定义了一个名为 runningTotal 的整数变量,用于存储即将返回的增量器的当前累计总和。这个变量初始化为 0。
The makeIncrementer(forIncrement:) function has a single Int parameter
with an argument label of forIncrement, and a parameter name of amount.
The argument value passed to this parameter specifies
how much runningTotal should be incremented by
each time the returned incrementer function is called.
The makeIncrementer function defines a nested function called incrementer,
which performs the actual incrementing.
This function simply adds amount to runningTotal, and returns the result.
makeIncrementer(forIncrement:) 函数有一个 Int 类型的参数,其外部参数名为 forIncrement,内部参数名称为 amount。该参数值指定每次调用 incrementer 时将要增加的值 runningTotal 是多少。makeIncrementer 函数定义了一个名为 incrementer 的嵌套函数,该函数执行实际的增加操作。此函数只是将 amount 增加到 runningTotal 上,并返回结果。
When considered in isolation,
the nested incrementer() function might seem unusual:
如果单独看这个嵌套的 incrementer() 函数,可能会觉得有些奇怪:
func incrementer() -> Int {
runningTotal += amount
return runningTotal
}The incrementer() function doesn't have any parameters,
and yet it refers to runningTotal and amount from within its function body.
It does this by capturing a reference to runningTotal and amount
from the surrounding function and using them within its own function body.
Capturing by reference ensures that runningTotal and amount don't disappear
when the call to makeIncrementer ends,
and also ensures that runningTotal is available
the next time the incrementer function is called.
incrementer() 函数没有任何参数,但它在函数体内引用了 runningTotal 和 amount。这是通过捕获外围函数中 runningTotal 和 amount 的 引用 来实现的,并在自己的函数体中使用这些引用。通过引用捕获可以确保当 makeIncrementer 函数调用结束时,runningTotal 和 amount 不会消失。同时,这也保证了在下次调用 incrementer 函数时,runningTotal 仍然可用。
Note · 注意
As an optimization, Swift may instead capture and store a copy of a value if that value isn't mutated by a closure, and if the value isn't mutated after the closure is created.
Swift also handles all memory management involved in disposing of variables when they're no longer needed.
作为一项优化,如果值不会被闭包改变,并且该值在创建闭包后不会改变,那么 Swift 可能会捕获并存储该值的 副本。
Swift 也会负责被捕获变量涉及的所有内存管理工作,包括释放不再需要的变量。
Here's an example of makeIncrementer in action:
下面是一个使用 makeIncrementer 的例子:
let incrementByTen = makeIncrementer(forIncrement: 10)This example sets a constant called incrementByTen
to refer to an incrementer function that adds 10 to
its runningTotal variable each time it's called.
Calling the function multiple times shows this behavior in action:
这个例子定义了一个名为 incrementByTen 的常量,它引用了一个增量器函数。这个函数每次被调用时都会将其 runningTotal 变量增加 10。多次调用这个函数可以看到这个行为的实际效果:
incrementByTen()
// returns a value of 10
incrementByTen()
// returns a value of 20
incrementByTen()
// returns a value of 30If you create a second incrementer,
it will have its own stored reference to a new, separate runningTotal variable:
如果你创建第二个增量器,它会有自己存储的引用,指向一个新的、独立的 runningTotal 变量:
let incrementBySeven = makeIncrementer(forIncrement: 7)
incrementBySeven()
// returns a value of 7Calling the original incrementer (incrementByTen) again
continues to increment its own runningTotal variable,
and doesn't affect the variable captured by incrementBySeven:
再次调用原来的增量器( incrementByTen )会继续增加它自己的 runningTotal 变量,而不会影响 incrementBySeven 捕获的变量:
incrementByTen()
// returns a value of 40Note · 注意
If you assign a closure to a property of a class instance, and the closure captures that instance by referring to the instance or its members, you will create a strong reference cycle between the closure and the instance. Swift uses capture lists to break these strong reference cycles. For more information, see Strong Reference Cycles for Closures.
如果将闭包赋值给类实例的属性,并且闭包通过引用实例或其成员来捕获该实例,则将在闭包和实例之间创建一个强循环引用。Swift 使用 捕获列表 来打破这些强循环引用。有关更多信息,请参阅 闭包的强引用循环.
Closures Are Reference Types 闭包是引用类型
In the example above,
incrementBySeven and incrementByTen are constants,
but the closures these constants refer to are still able to increment
the runningTotal variables that they have captured.
This is because functions and closures are reference types.
在上面的示例中,incrementBySeven 和 incrementByTen 是常量,但这些常量引用的闭包仍然能够递增它们捕获的 runningTotal 变量。这是因为函数和闭包是 引用类型。
Whenever you assign a function or a closure to a constant or a variable,
you are actually setting that constant or variable to be
a reference to the function or closure.
In the example above,
it's the choice of closure that incrementByTen refers to that's constant,
and not the contents of the closure itself.
每当你将函数或闭包赋值给一个常量或变量时,你实际上是在将该常量或变量设置为对函数或闭包的 引用。在上面的示例中,incrementByTen 引用 的闭包选择是常量,而不是闭包本身的内容。
This also means that if you assign a closure to two different constants or variables, both of those constants or variables refer to the same closure.
这也意味着,如果将闭包分配给两个不同的常量或变量,则这两个常量或变量都引用同一闭包。
let alsoIncrementByTen = incrementByTen
alsoIncrementByTen()
// returns a value of 50
incrementByTen()
// returns a value of 60The example above shows that calling alsoIncrementByTen
is the same as calling incrementByTen.
Because both of them refer to the same closure,
they both increment and return the same running total.
上面的示例表明,调用 alsoIncrementByTen 与调用 incrementByTen 相同。由于它们都引用相同的闭包,因此它们都会递增并返回相同的 runningTotal 值。
Escaping Closures 逃逸闭包
A closure is said to escape a function
when the closure is passed as an argument to the function,
but is called after the function returns.
When you declare a function that takes a closure as one of its parameters,
you can write @escaping before the parameter's type
to indicate that the closure is allowed to escape.
当闭包作为参数传递给函数,但是这个闭包在函数返回之后才被执行,该闭包被称为 逃逸 函数。当你声明一个将闭包作为其参数之一的函数时,你可以在参数的类型之前写入 @escaping,以表示这个闭包是允许逃逸的。
One way that a closure can escape is by being stored in a variable that's defined outside the function. As an example, many functions that start an asynchronous operation take a closure argument as a completion handler. The function returns after it starts the operation, but the closure isn't called until the operation is completed --- the closure needs to escape, to be called later. For example:
闭包逃逸的一种常见方式是将其存储在函数外部定义的变量中。例如,许多启动异步操作的函数会接受一个闭包作为完成处理器(completion handler)。这种函数在启动操作后就会返回,但闭包要等到操作完成后才会被调用——这就需要闭包逃逸,以便稍后调用。示例如下:
var completionHandlers: [() -> Void] = []
func someFunctionWithEscapingClosure(completionHandler: @escaping () -> Void) {
completionHandlers.append(completionHandler)
}The someFunctionWithEscapingClosure(_:) function takes a closure as its argument
and adds it to an array that's declared outside the function.
If you didn't mark the parameter of this function with @escaping,
you would get a compile-time error.
someFunctionWithEscapingClosure(_:) 函数将闭包作为其参数,并将其添加到函数外部声明的数组中。如果不用 @escaping 标记此函数的参数,则会收到编译错误。
An escaping closure that refers to self
needs special consideration if self refers to an instance of a class.
Capturing self in an escaping closure
makes it easy to accidentally create a strong reference cycle.
For information about reference cycles,
see Automatic Reference Counting.
在逃逸闭包中引用 self 时,如果 self 指向一个类的实例,就需要特别注意。在逃逸闭包中捕获 self 很容易意外创建强引用循环。关于引用循环的更多信息,请参见 自动引用计数 。
Normally, a closure captures variables implicitly
by using them in the body of the closure,
but in this case you need to be explicit.
If you want to capture self,
write self explicitly when you use it,
or include self in the closure's capture list.
Writing self explicitly lets you express your intent,
and reminds you to confirm that there isn't a reference cycle.
For example, in the code below,
the closure passed to someFunctionWithEscapingClosure(_:)
refers to self explicitly.
In contrast, the closure passed to someFunctionWithNonescapingClosure(_:)
is a nonescaping closure, which means it can refer to self implicitly.
通常情况下,闭包会通过在其体内使用变量来隐式捕获这些变量,但在这种情况下,你需要显式地进行捕获。如果你想捕获 self,在使用时要明确写出 self,或者将 self 包含在闭包的捕获列表中。明确地写出 self 可以表达你的意图,并提醒你检查是否存在引用循环。例如,在下面的代码中,传递给 someFunctionWithEscapingClosure(_:) 的闭包明确地引用了 self。相比之下,传递给 someFunctionWithNonescapingClosure(_:) 的闭包是一个非逃逸闭包,这意味着它可以隐式地引用 self。
func someFunctionWithNonescapingClosure(closure: () -> Void) {
closure()
}
class SomeClass {
var x = 10
func doSomething() {
someFunctionWithEscapingClosure { self.x = 100 }
someFunctionWithNonescapingClosure { x = 200 }
}
}
let instance = SomeClass()
instance.doSomething()
print(instance.x)
// Prints "200".
completionHandlers.first?()
print(instance.x)
// Prints "100".Here's a version of doSomething() that captures self
by including it in the closure's capture list,
and then refers to self implicitly:
这是 doSomething() 的一个版本,它通过将 self 包含在闭包的捕获列表中来捕获 self,然后隐式引用 self:
class SomeOtherClass {
var x = 10
func doSomething() {
someFunctionWithEscapingClosure { [self] in x = 100 }
someFunctionWithNonescapingClosure { x = 200 }
}
}If self is an instance of a structure or an enumeration,
you can always refer to self implicitly.
However,
an escaping closure can't capture a mutable reference to self
when self is an instance of a structure or an enumeration.
Structures and enumerations don’t allow shared mutability,
as discussed in Structures and Enumerations Are Value Types.
如果 self 是结构体或枚举的实例,则始终可以隐式引用 self。但是逃逸闭包无法捕获其对 self 的可变引用。结构体和枚举不允许共享可变性,如 结构体和枚举是值类型 中所述。
struct SomeStruct {
var x = 10
mutating func doSomething() {
someFunctionWithNonescapingClosure { x = 200 } // OK
someFunctionWithEscapingClosure { x = 100 } // Error
}
}The call to the someFunctionWithEscapingClosure function
in the example above is an error
because it's inside a mutating method,
so self is mutable.
That violates the rule that escaping closures can't capture
a mutable reference to self for structures.
在上面的示例中,对 someFunctionWithEscapingClosure 函数的调用是一个错误,因为它位于一个可变函数中,因此 self 是可变的。这违反了规则,即逃逸闭包不能捕获对结构的 self 的可变引用。
Autoclosures 自动闭包
An autoclosure is a closure that's automatically created to wrap an expression that's being passed as an argument to a function. It doesn't take any arguments, and when it's called, it returns the value of the expression that's wrapped inside of it. This syntactic convenience lets you omit braces around a function's parameter by writing a normal expression instead of an explicit closure.
自动闭包 是一种自动创建的闭包,用于包装作为参数传递给函数的表达式。它不接受任何参数,当它被调用时,它返回包裹在其内部的表达式的值。这种便利语法让你能够省略闭包的大括号,用一个普通的表达式来代替显式的闭包。
It's common to call functions that take autoclosures,
but it's not common to implement that kind of function.
For example,
the assert(condition:message:file:line:) function
takes an autoclosure for its condition and message parameters;
its condition parameter is evaluated only in debug builds
and its message parameter is evaluated only if condition is false.
我们经常会 调用 采用自动闭包的函数,但是很少去 实现 这样的函数。例如,assert(condition:message:file:line:) 函数接受自动闭包作为它的 condition 和 message 参数; 其 condition 参数仅在 Debug 版本中计算,而其 message 参数仅在 condition 为 false 时计算。
An autoclosure lets you delay evaluation, because the code inside isn't run until you call the closure. Delaying evaluation is useful for code that has side effects or is computationally expensive, because it lets you control when that code is evaluated. The code below shows how a closure delays evaluation.
自动闭包允许你延迟计算,因为在你调用这个闭包之前,内部代码不会运行。延迟计算对于有副作用或高计算成本的代码非常有用,因为它使得你能控制代码的执行时机。下面的代码展示了闭包如何延时计算。
var customersInLine = ["Chris", "Alex", "Ewa", "Barry", "Daniella"]
print(customersInLine.count)
// Prints "5".
let customerProvider = { customersInLine.remove(at: 0) }
print(customersInLine.count)
// Prints "5".
print("Now serving \(customerProvider())!")
// Prints "Now serving Chris!"
print(customersInLine.count)
// Prints "4".Even though the first element of the customersInLine array is removed
by the code inside the closure,
the array element isn't removed until the closure is actually called.
If the closure is never called,
the expression inside the closure is never evaluated,
which means the array element is never removed.
Note that the type of customerProvider isn't String
but () -> String ---
a function with no parameters that returns a string.
即使 customersInLine 数组的第一个元素被闭包内的代码删除,但在实际调用闭包之前,不会删除数组中的元素。如果从不调用闭包,则永远不会计算闭包内的表达式,这意味着永远不会删除数组元素。请注意,customerProvider 的类型不是 String,而是 () -> String --- 一个返回字符串的没有参数的函数。
You get the same behavior of delayed evaluation when you pass a closure as an argument to a function.
将闭包作为参数传递给函数时,你能获得同样的延时计算行为。
// customersInLine is ["Alex", "Ewa", "Barry", "Daniella"]
func serve(customer customerProvider: () -> String) {
print("Now serving \(customerProvider())!")
}
serve(customer: { customersInLine.remove(at: 0) } )
// Prints "Now serving Alex!"The serve(customer:) function in the listing above
takes an explicit closure that returns a customer's name.
The version of serve(customer:) below
performs the same operation but, instead of taking an explicit closure,
it takes an autoclosure
by marking its parameter's type with the @autoclosure attribute.
Now you can call the function
as if it took a String argument instead of a closure.
The argument is automatically converted to a closure,
because the customerProvider parameter's type is marked
with the @autoclosure attribute.
上面列表中的 serve(customer:) 函数接受一个返回顾客名字的显式闭包。下面这个版本的 serve(customer:) 执行相同的操作,但它不接受显式的闭包,而是通过将形参类型标记为 @autoclosure 特性来接受一个自动闭包。现在你可以像调用接受 String 实参而不是闭包的函数一样来调用它。因为 customerProvider 形参的类型被标记为 @autoclosure 特性,所以实参会自动转换为闭包。
// customersInLine is ["Ewa", "Barry", "Daniella"]
func serve(customer customerProvider: @autoclosure () -> String) {
print("Now serving \(customerProvider())!")
}
serve(customer: customersInLine.remove(at: 0))
// Prints "Now serving Ewa!"Note · 注意
Overusing autoclosures can make your code hard to understand. The context and function name should make it clear that evaluation is being deferred.
过度使用自动闭包可能会使你的代码难以理解。上下文和函数名称应明确表示计算正在被推迟。
If you want an autoclosure that's allowed to escape,
use both the @autoclosure and @escaping attributes.
The @escaping attribute is described above in Escaping Closures.
如果你想要允许一个自动闭包可以逃逸,请同时使用 @autoclosure 和 @escaping 属性。@escaping 属性在上面的 逃逸闭包 中进行了描述。
// customersInLine is ["Barry", "Daniella"]
var customerProviders: [() -> String] = []
func collectCustomerProviders(_ customerProvider: @autoclosure @escaping () -> String) {
customerProviders.append(customerProvider)
}
collectCustomerProviders(customersInLine.remove(at: 0))
collectCustomerProviders(customersInLine.remove(at: 0))
print("Collected \(customerProviders.count) closures.")
// Prints "Collected 2 closures."
for customerProvider in customerProviders {
print("Now serving \(customerProvider())!")
}
// Prints "Now serving Barry!"
// Prints "Now serving Daniella!"In the code above,
instead of calling the closure passed to it
as its customerProvider argument,
the collectCustomerProviders(_:) function
appends the closure to the customerProviders array.
The array is declared outside the scope of the function,
which means the closures in the array can be executed after the function returns.
As a result,
the value of the customerProvider argument
must be allowed to escape the function's scope.
在上面的代码中,collectCustomerProviders(_:) 函数将闭包追加到 customerProviders 数组中,而不是调用作为其 customerProvider 参数传递给它的闭包。数组是在函数的作用域之外声明的,这意味着数组中的闭包可以在函数返回后执行。因此 customerProvider 参数必须允许逃逸出函数的作用域。