闭包(Closures)函数/表达式

在其他语言中,闭包函数也可能叫代码块(blocks)或者匿名函数(lambdas)。

全局函数、嵌套函数和闭包表达式的区别

  • 全局函数是一种有名字但不能捕捉上下文的常量或变量值的闭包函数
  • 嵌套函数是一种有名字并且能捕捉包括它的函数的常量或变量值的闭包函数
  • 闭包表达式没有名字,轻量,能够捕捉上下文的常量或变量值

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 do not 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.org

可以作为参数传值

闭包函数允许被整块赋值给变量,函数可以接收闭包函数作为参数,避免了额外利用对象传值的麻烦。比如对数组排序的场景下,排序函数可以接收一个闭包函数用于描述排序的依据。

可以捕获变量并存储副本

闭包函数支持捕捉上下文中的任何常量或变量,并且一个闭包函数对象会存储捕捉到的常量或变量的副本。

Closures can capture and store references to any constants and variables from the context in which they are defined.

Swift.org

Swift代码示例:

func makeCounter() -> () -> Int {
    var count = 0
    func counter() -> Int {
        count = count + 1
        return count
    }
    return counter
}

let aCount = makeCounter()
print(aCount());1
print(aCount());2

let bCount = makeCounter()
print(bCount());1
print(bCount());2

发表评论

电子邮件地址不会被公开。