# 捕获变量或常量

闭包可以在其被定义的上下文中捕获常量或变量。即使定义这些常量和变量的原作用域已经不存在，闭包仍然可以在闭包函数体内引用和修改这些值

## 1. 捕获的方式是引用捕获

闭包是以**引用的方式捕获常量和变量**。捕获的变量可以在闭包中修改，并且会影响原本的变量。

```swift
var a = 1

// 引用捕获a
let function = {() in
    a += 1
}

function()
function()
print(a)        // a = 3
```

> 为了优化，如果一个值不会被闭包改变，或者在闭包创建后不会改变，Swift 可能会改为捕获并保存一份对值的拷贝。

## 2. 闭包会管理捕获变量或常量的生命周期

Swift 负责被捕获变量的所有内存管理工作.即使捕获的常量和变量的原作用域已经不存在，闭包仍然可以在闭包函数体内引用和修改这些值。

```swift

var function : (() -> Void )!


if true{
    var a = 1
    function = {() in
    a += 1
    }
}

// a 看似生命周期结束，但闭包管理了a的生命周期，仍然可以访问
function()
function()

```


---

# 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/4.-bu-huo-bian-liang-huo-chang-liang.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.
