# 类和结构体

`Swift`支持面向对象编程，支持自定义类型。`Swift`中的自定义类型被分为`结构体Struct`和`类Class`。

`Struct`是值类型，例如`Int`，`Float`，`Array`，`Set`，`String`，`Dictionary`等类型都是Struct类型；

`Class`是引用类型，例如 闭包表达式，`UIKit`框架的类型

## 1. 结构体和类的对比

### 1.1 相同点

* 定义储存属性和计算属性
* 定义方法用于提供功能
* 定义下标操作用于通过下标语法访问它们的值
* 定义构造器用于设置初始值
* 通过扩展以增加默认实现之外的功能
* 遵循协议以提供某种标准功能

### 1.2 不同点

* 结构体是值类型；类是引用类型
* 继承允许一个类继承另一个类的特征(继承性)
* 类型转换允许在运行时检查和解释一个类实例的类型（动态性）
* 析构器允许一个类实例释放任何其所被分配的资源 (析构器)
* 引用计数允许对一个类的多次引用 (引用计数)

> 类支持的附加功能是增加复杂性为代价的。作为一般准则优先使用Struct，必要时使用Class。 更多的比较参考[在结构体和类之间选择](https://developer.apple.com/documentation/swift/choosing_between_structures_and_classes)

## 2. 定义Class和Struct

```swift
struct SomeStructure {
    // 在这里定义结构体
}
class SomeClass {
    // 在这里定义类
}

```

## 3. 结构体和枚举是值类型

值类型是这样一种类型，当它被赋值给一个变量、常量或者被传递给一个函数的时候，其值(即每一个成员)会被拷贝。

Swift 中所有的基本类型：整数（integer）、浮点数（floating-point number）、布尔值（boolean）、字符串（string)、数组（array）和字典（dictionary），都是值类型，其底层也是使用结构体实现的。

> 标准库定义的集合，如数组，集合，字典和字符串，都会采用**写时拷贝**机制进行优化。

![](https://docs.swift.org/swift-book/_images/sharedStateStruct_2x.png)

## 4. 类是引用类型

引用类型在赋值是不会拷贝对象的值，而是传递对象的引用（指针）。

![](https://docs.swift.org/swift-book/_images/sharedStateClass_2x.png)

### 4.1 恒等运算符

为了判定两个常量或者变量是否引用同一个类实例，Swift提出了恒等运算符

```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/9.-lei-he-jie-gou-ti/1.-lei-he-jie-gou-ti.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.
