# 属性观察器

`属性观察器`监控和响应属性值的变化，每次属性被设置值的时候都会调用属性观察器，即使新值和当前值相同的时候也不例外。

你可以在定义类为`存储属性`添加`属性观察器`;也可以为继承父类的`存储属性`和`计算属性`添加`属性观察器`。

```swift

class StepCounter {
    var totalSteps: Int = 0 {
        willSet(newTotalSteps) {
            print("将 totalSteps 的值设置为 \(newTotalSteps)")
        }
        didSet {
            if totalSteps > oldValue  {
                print("增加了 \(totalSteps - oldValue) 步")
            }
        }
    }
}

```

在`属性观察器`中可以使用默认参数`newValue`和`oldValue`，访问新值和原本的值

## newValue不可以修改

![](https://pic.existorlive.cn/%E6%88%AA%E5%B1%8F2020-11-30%20%E4%B8%8A%E5%8D%885.45.17.png)

`newValue`是不可以修改的。

## 在属性观察器中访问属性不会调用到属性观察器

```swift

class StepCounter {
    var totalSteps: Int = 0 {
        willSet(newTotalSteps) {
            print("将 totalSteps 的值设置为 \(newTotalSteps)")
        }
        didSet {
            if totalSteps > oldValue  {
               totalSteps = oldValue    // 可以修改新赋的值
            }
        }
    }
}

```

## 存储属性的初始化不会触发属性观察器

存储属性在定义时提供初始值或者在构造器中初始化不会触发属性观察器


---

# 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/9.-lei-he-jie-gou-ti/shu-xing/2.2-shu-xing-guan-cha-qi.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.
