# 闭包

**闭包**是自包含的函数代码块，可以在代码中被传递和使用。

Swift 中的闭包与 C 和 Objective-C 中的 **代码块(Block)** 以及其他一些编程语言中的 **匿名函数(Lambda)** 比较相似。

**闭包**可以捕获和存储其所在上下文中任意常量和变量的**引用**。被称为**包裹常量和变量**。

Swift 会为你管理在捕获过程中涉及到的所有内存操作。

闭包采用如下三种形式之一：

* **全局函数**是一个有名字但不会捕获任何值的闭包
* **嵌套函数**是一个有名字并可以捕获其封闭函数域内值的闭包
* **闭包表达式**是一个利用轻量级语法所写的可以捕获其上下文中变量或常量值的匿名闭包

***


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://gitbook.existorlive.cn/kai-fa-yu-yan-xue-xi/swift/7.-bi-bao/1.-bi-bao.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
