# 10.Struct与Class

## Swift 中的类型

* Types
  * 命名类型
    * protocol
    * enum
    * struct
    * class
  * 复合类型
    * tuple
    * function

> 实际上其他类型都是通过命名类型创建的

## Struct Class Enum

> Swift 提供了多种结构化存储数据的方式，他们是：Struct、Class、Enum Swift 表中库中绝大多数类型都是Struct，Class、Enum只有很小一部分

### 共同点：

* 都可以用 protocol
* 都可以使用 extension
* 都可以使用泛型

### 如何选择

根据对象生命周期形态，把使用的类型分成两大类

* 必须具有明确生命周期，被明确的初始化，使用，释放
  * 用Class
  * 例如：
    * 数据库连接，管理对象等
* 没有明确的生命周期
  * 用Struct或Enum
  * 例如：
    * 不用修改只是用来使用其值的

### Struct值类型本质

某个属性诗歌结构体，改变其某个属性，也会重新赋值一个新对象

## 值类型和引用类型

### 差异对比

* 引用类型必须指明`init`方法
* 引用类型关注的是对象本身
  * 使用值类型创建新对象时将会复制
  * 使用引用类型时，新变量将引用同一个对象
* 引用类型的默认值是可以修改的
  * 给Struct的方法默认是只读的。如果要修改要用`mutating`修饰
  * `class`中不用

## 参考

> <https://www.jianshu.com/p/a10f554ac63b> <https://juejin.im/post/5c653aa6e51d457fbf5dc298>


---

# 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://ryukiedev.gitbook.io/wiki/swift/struct-yu-class.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.
